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
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Standard Template Library
    Object Oriented ProgrammingTopic 22 of 24

    Standard Template Library

    7 minread
    1,124words
    Intermediatelevel

    Standard Template Library (STL) in C++

    The Standard Template Library (STL) is a powerful set of C++ template classes to implement generic data structures and algorithms. STL provides a collection of template classes and functions, which allows programmers to implement complex data structures and algorithms without the need to create them from scratch.

    The main components of the STL include:

    1. Containers: Used to store objects and manage collections of data.
    2. Algorithms: A set of functions to perform operations like sorting, searching, etc., on data stored in containers.
    3. Iterators: Used to traverse through elements of containers.
    4. Function Objects (Functors): Objects that can be called as if they were functions.
    5. Allocators: Responsible for memory management of data within containers.

    Components of STL

    1. Containers

    Containers are used to store and organize data. They can be divided into two categories:

    • Sequence containers: Store elements in a linear fashion (e.g., vector, list, deque).
    • Associative containers: Store elements in a way that allows fast lookup based on keys (e.g., map, set).
    Sequence Containers:
    • Vector: A dynamic array that grows automatically as elements are added. Allows random access to elements.
    • List: A doubly linked list that allows efficient insertions and deletions from both ends.
    • Deque: A double-ended queue that allows efficient insertion and deletion at both ends.
    • Array: A fixed-size container for storing elements. Similar to a regular C++ array, but with additional functionalities.

    Example:

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
        
        // Access elements using index
        std::cout << "Element at index 2: " << vec[2] << std::endl;
    
        // Add element to the end
        vec.push_back(6);
        
        std::cout << "Last element: " << vec.back() << std::endl;
        return 0;
    }
    
    Associative Containers:
    • Set: Stores unique elements in sorted order. Provides fast search operations.
    • Map: Stores key-value pairs in sorted order based on keys. Each key is unique.
    • Multiset: Like a set but allows duplicate elements.
    • Multimap: Like a map but allows multiple values for the same key.

    Example:

    #include <iostream>
    #include <map>
    
    int main() {
        std::map<int, std::string> m;
        m[1] = "one";
        m[2] = "two";
        m[3] = "three";
    
        for (auto& pair : m) {
            std::cout << pair.first << ": " << pair.second << std::endl;
        }
        
        return 0;
    }
    

    2. Algorithms

    The STL provides a variety of algorithms to manipulate data in containers. These algorithms work seamlessly with any container that provides iterators.

    Some of the common STL algorithms include:

    • Sorting: std::sort(), std::stable_sort()
    • Searching: std::find(), std::binary_search()
    • Modification: std::reverse(), std::transform()
    • Comparison: std::equal(), std::lexicographical_compare()
    • Counting: std::count(), std::count_if()

    Example:

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {5, 3, 8, 1, 4};
        
        // Sorting vector
        std::sort(vec.begin(), vec.end());
    
        // Printing sorted vector
        for (int num : vec) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    

    3. Iterators

    Iterators are objects that allow traversal through the elements of a container. They provide a way to access elements of a container in a generalized manner, making it easy to write algorithms that work with different types of containers.

    There are several types of iterators:

    • Input Iterator: Can read data from a container (e.g., std::istream_iterator).
    • Output Iterator: Can write data to a container (e.g., std::ostream_iterator).
    • Forward Iterator: Can read and write data, can move forward.
    • Bidirectional Iterator: Can read and write data, can move forward and backward.
    • Random Access Iterator: Supports random access, like a pointer (e.g., for vectors and arrays).

    Example of using iterators to traverse a vector:

    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        // Using an iterator to traverse and print elements
        for (auto it = vec.begin(); it != vec.end(); ++it) {
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    

    4. Function Objects (Functors)

    A function object (or functor) is an object that can be used as if it were a function. It is any object that overloads the operator().

    Function objects are useful when you need a custom function to be passed as a parameter to algorithms or containers, especially when you want to capture additional state.

    Example:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    class Print {
    public:
        void operator()(int value) const {
            std::cout << value << " ";
        }
    };
    
    int main() {
        std::vector<int> vec = {1, 2, 3, 4, 5};
    
        // Using a function object with an algorithm
        std::for_each(vec.begin(), vec.end(), Print());
        std::cout << std::endl;
    
        return 0;
    }
    

    5. Allocators

    Allocators are responsible for handling memory allocation and deallocation for STL containers. Most STL containers (such as std::vector or std::list) use the default allocator, but custom allocators can be implemented if needed to control memory management more precisely.

    Advantages of STL

    1. Efficiency: STL provides highly optimized algorithms and data structures that are tested and proven for performance.
    2. Generic Programming: Through templates, STL allows you to write code that works with any data type, providing flexibility.
    3. Standardization: Since STL is part of the C++ Standard Library, it is widely supported across different compilers and platforms.
    4. Reusability: STL algorithms and containers are reusable and abstract away the underlying complexities of data structures.
    5. Extensibility: You can easily extend STL with your own containers, algorithms, and function objects.

    Disadvantages of STL

    1. Complexity: STL introduces some level of complexity, especially for beginners who are not familiar with templates and iterators.
    2. Code Size: Due to template metaprogramming, STL can cause code bloat, leading to larger executable sizes if many templates are instantiated.
    3. Compile-time Overhead: Templates are resolved at compile time, which can lead to longer compilation times, especially when many templates are used.

    Conclusion

    The Standard Template Library (STL) is an essential part of C++ that provides a set of powerful, flexible, and reusable templates for common data structures and algorithms. With containers, algorithms, iterators, and other components, STL helps developers write efficient, generic, and maintainable code. Whether you're implementing a custom data structure or using a pre-built algorithm, STL offers significant advantages for both performance and productivity.

    Previous topic 21
    Class Templates
    Next topic 23
    Object Streams: Data and Object Serialization

    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 time7 min
      Word count1,124
      Code examples0
      DifficultyIntermediate