ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Standard template library
    Object Oriented ProgrammingTopic 20 of 23

    Standard template library

    8 minread
    1,281words
    Intermediatelevel

    Standard Template Library (STL) in C++

    The Standard Template Library (STL) is a powerful set of C++ template classes to provide general-purpose, reusable algorithms and data structures. It is part of the C++ Standard Library and significantly simplifies the development process by providing ready-to-use components for common tasks.

    The STL is composed of containers, iterators, algorithms, and function objects. These components help you write efficient and generic code that can work with any data type, enhancing the reusability and flexibility of your programs.


    1. Components of STL

    The STL consists of four main components:

    1. Containers
    2. Iterators
    3. Algorithms
    4. Function Objects

    2. Containers

    Containers are data structures that store collections of objects or data. The STL provides several types of containers that can be categorized into:

    • Sequence Containers: Store elements in a linear sequence.

      • vector: Dynamic array, allows fast access and efficient appending.
      • deque: Double-ended queue, allows fast access from both ends.
      • list: Doubly linked list, allows fast insertions and deletions at any position.
      • array: Fixed-size array, a wrapper around standard arrays.
      • forward_list: Singly linked list, more memory efficient than list.
    • Associative Containers: Store elements in a sorted order, allowing fast searching, insertion, and deletion.

      • set: Stores unique elements in a sorted order.
      • map: Stores key-value pairs, keys are unique, and values can be modified.
      • multiset: Like set, but allows duplicate elements.
      • multimap: Like map, but allows duplicate keys.
    • Unordered Containers: Store elements without any specific order, but offer fast access.

      • unordered_set: Stores unique elements in no specific order.
      • unordered_map: Stores key-value pairs without any order, offering fast lookups.
      • unordered_multiset: Like unordered_set, but allows duplicates.
      • unordered_multimap: Like unordered_map, but allows duplicate keys.

    Example: Using a vector container

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<int> vec = {1, 2, 3, 4, 5};  // Create a vector of integers
    
        // Adding elements to the vector
        vec.push_back(6);
    
        // Displaying elements of the vector
        for (int i = 0; i < vec.size(); i++) {
            cout << vec[i] << " ";
        }
    
        return 0;
    }
    

    3. Iterators

    Iterators are used to traverse through the elements in containers. They act as pointers and allow you to access container elements in a uniform way. Iterators work with all STL containers and support operations like moving forward, backward, and modifying container contents.

    Types of Iterators:

    • Input Iterator: Reads data from the container.
    • Output Iterator: Writes data to the container.
    • Forward Iterator: Moves forward through the container.
    • Bidirectional Iterator: Moves both forward and backward.
    • Random Access Iterator: Supports all the operations of a pointer, i.e., it can jump to any position in the container.

    Example: Using an Iterator with vector

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        vector<int> vec = {1, 2, 3, 4, 5};
    
        // Using iterator to traverse the vector
        for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
            cout << *it << " ";  // Dereferencing iterator to get element
        }
    
        return 0;
    }
    

    4. Algorithms

    Algorithms are functions provided by the STL to perform operations on containers. They are highly optimized and generic, meaning they can be used with any container that supports iterators. Common operations include sorting, searching, modifying, and manipulating data.

    Some commonly used algorithms:

    • sort(): Sorts the elements in a container.
    • find(): Searches for an element in a container.
    • reverse(): Reverses the order of elements in a container.
    • count(): Counts the occurrences of a value.
    • max_element(): Returns the largest element.
    • min_element(): Returns the smallest element.

    Example: Using the sort and find Algorithms

    #include <iostream>
    #include <vector>
    #include <algorithm>  // For sort and find
    using namespace std;
    
    int main() {
        vector<int> vec = {5, 2, 9, 1, 5, 6};
    
        // Sorting the vector
        sort(vec.begin(), vec.end());
    
        // Displaying sorted vector
        cout << "Sorted vector: ";
        for (int num : vec) {
            cout << num << " ";
        }
        cout << endl;
    
        // Using find algorithm to locate an element
        auto it = find(vec.begin(), vec.end(), 9);
        if (it != vec.end()) {
            cout << "Element 9 found at position: " << distance(vec.begin(), it) << endl;
        } else {
            cout << "Element 9 not found" << endl;
        }
    
        return 0;
    }
    

    Explanation:

    • The sort() function sorts the elements of the vector in ascending order.
    • The find() function searches for the value 9 in the vector and returns an iterator pointing to it.

    5. Function Objects (Functors)

    A function object (or functor) is any object that can be called as if it were a function. In STL, function objects are used to define custom behavior for algorithms. They are often used when you need more flexibility or state within an algorithm.

    Example: Function Object to Compare Values

    #include <iostream>
    #include <vector>
    #include <algorithm>  // For sort
    using namespace std;
    
    class Compare {
    public:
        bool operator()(int a, int b) {
            return a > b;  // Custom comparison: sort in descending order
        }
    };
    
    int main() {
        vector<int> vec = {5, 2, 9, 1, 5, 6};
    
        // Sorting using function object
        sort(vec.begin(), vec.end(), Compare());
    
        // Displaying sorted vector
        cout << "Sorted vector (descending): ";
        for (int num : vec) {
            cout << num << " ";
        }
    
        return 0;
    }
    

    Explanation:

    • The Compare class overloads the operator() to define a custom comparison for sorting in descending order.
    • This function object is then used in the sort() algorithm to sort the vector.

    6. STL Memory Management

    STL containers like vector, deque, and list manage memory automatically, meaning they handle dynamic allocation and deallocation of memory for the elements they store. However, some containers, like array and vector, may offer better performance and optimization in terms of memory management, depending on the use case.

    • Dynamic Allocation: For containers like vector, elements are dynamically allocated, and memory is managed automatically as elements are added or removed.
    • Smart Pointers: C++11 introduced smart pointers like std::unique_ptr and std::shared_ptr, which can be used in conjunction with STL containers to manage memory more safely and efficiently.

    7. Summary of STL Components

    1. Containers: Hold collections of data (e.g., vector, list, map).
    2. Iterators: Provide a way to access and traverse elements in containers.
    3. Algorithms: Perform operations like sorting, searching, and modifying on containers.
    4. Function Objects: Define custom behavior for algorithms, often providing more flexibility.

    8. Advantages of STL

    • Efficiency: STL containers and algorithms are highly optimized and designed for performance.
    • Generality: STL components work with any data type, making them reusable and flexible.
    • Modularity: The modular nature of STL allows you to select only the components you need for your program.
    • Code Reusability: Using STL means you don’t need to write common data structures and algorithms from scratch.

    The STL in C++ is an incredibly powerful tool that simplifies common programming tasks, reduces development time, and improves code maintainability. By leveraging STL containers, algorithms, iterators, and function objects, you can write cleaner, more efficient, and reusable C++ code.

    Previous topic 19
    Function & class templates
    Next topic 21
    Object streams

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,281
      Code examples0
      DifficultyIntermediate