ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-211Standard Template Libr…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-211

    Object Oriented Programming

    Progress0 / 24 done
    Topics24
    1History and Advantages
    2Terminology and Features3Classes and Objects4Data Encapsulation5Constructors and Destructors6Access Modifiers7Const vs Non-Const Functions8Static Data Members and Functions9Function Overloading10Operator Overloading11Identification of Classes and Their Relationships12Composition13Aggregation14Inheritance15Multiple Inheritances16Polymorphism17Abstract Classes18Interfaces19Generic Programming Concepts20Function Templates21Class Templates22Standard Template Library
    23Data and Object Serialization24Exception Handling
    7 min read
    Topic 22 of 24
    Topic Study Note Illustration
    22

    Standard Template Library

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming