The Standard Template Library (STL) is used to perform common programming tasks easily using ready-made classes and functions.
In this chapter, you will learn about C++ STL, its components, and how STL containers and algorithms are used in C++ programs.
In C++, a standard template library (STL) is a powerful set of template classes and functions that provide general data structures and algorithms. It allows developers to use well-optimized implementation of general programming components, such as dynamic arrays, linked lists, stacks, queues, sets, maps, and various algorithms.
The STL mainly consists of the following components:
| Component | Description |
|---|---|
| Containers | These are used to store and organize data. |
| Algorithms | These are used to perform operations such as sorting, searching, and manipulation. |
| Iterators | Iterators are used to access elements of containers. |
The following example demonstrates the use of an STL container and an STL algorithm.
In this example, the vector container is used to store integer values, and the sort() algorithm is used to sort the elements.
Output:
Sorted numbers: 1 2 4 7 8
Explanation:
In the above example, the vector<int> is an STL container used to store integer values. The sort() function is an STL algorithm that sorts the elements of the vector in ascending order.
C++ STL is mainly classified into the following four components.
Now, we will discuss these C++ STL types one by one.
Containers can be described as the objects that hold the data of the same type. Containers are used to implement different data structures, such as arrays, lists, trees, etc.
Following are the containers that provide the details of all the containers as well as the header file and the type of iterator associated with them :
| Container | Description | Header file | iterator |
|---|---|---|---|
| vector | vector is a class that creates a dynamic array allowing insertions and deletions at the back. | <vector> | Random access |
| list | list is the sequence containers that allow the insertions and deletions from anywhere. | <list> | Bidirectional |
| deque | deque is the double ended queue that allows the insertion and deletion from both the ends. | <deque> | Random access |
| set | set is an associate container for storing unique sets. | <set> | Bidirectional |
| multiset | Multiset is an associate container for storing non- unique sets. | <set> | Bidirectional |
| map | Map is an associate container for storing unique key-value pairs, i.e. each key is associated with only one value(one to one mapping). | <map> | Bidirectional |
| multimap | multimap is an associate container for storing key- value pair, and each key can be associated with more than one value. | <map> | Bidirectional |
| stack | It follows last in first out(LIFO). | <stack> | No iterator |
| queue | It follows first in first out(FIFO). | <queue> | No iterator |
| Priority-queue | First element out is always the highest priority element. | <queue> | No iterator |
Sequence containers store elements in a linear order and also allow indexed access.
Let's take an instance to demonstrate the Sequence Containers in C++.
Output:
Vector elements: 10 20 30 40 50
Explanation:
In this example, we initializes a vector with elements {10, 20, 30, 40} and then adds 50 at the end using push_back() function. Finally, it prints all the vector elements using a range-based for loop.
Associative containers store elements in key-based sorted order and automatically maintain this ordering. They organize data as key-value pairs and provide efficient lookup, insertion, and deletion based on the key.
Let's take an instance to demonstrate the Associative containers in C++.
Output:
ID: 101, Name: Alice ID: 102, Name: Bob ID: 103, Name: Charlie
Explanation:
In this example, we have taken a map container that stores key-value pairs in sorted order. It inserts student IDs (101, 102, 103) as keys and names (Alice, Bob, Charlie) as values. Finally, it iterates through the map using a range-based for loop to print each ID and name.
These containers are the essential part of the C++ STL, which stores in inaccurate order and enables fast retrieval of elements using hash tables. Unordered associative containers do not maintain any order. Several unordered associative containers in C++ are as follows:
Let's take an instance to demonstrate the unordered associative containers in C++.
Output:
Mango: 5 Banana: 20 Apple: 10 Orange: 15
Explanation:
In this example, we have taken a unordered_map that stores key-value pairs in an unordered manner for fast lookups. It initializes a map with fruit names as keys and their counts as values then insert "Mango". Finally, it iterates through the map using a range-based for loop to print each fruit and its count.
In C++, STL iterators are pointer-like entities that are used to access the individual elements in a container. Iterators are moved sequentially from one element to another element. This process is known as iterating through a container.
The iterator contains mainly two functions:
Iterators are mainly divided into five categories:
1. Input iterator:
An Input iterator is an iterator that allows the program to read the values from the container by dereferencing, but it does not allow those values to be modified. It is a one-way repetition, which means that it can only be incremented (++)-not decremented (-). Input iterators are usually used in single-pass algorithms where data is read sequentially.
2. Output iterator:
An output iterator is similar to the input iterator, except that it allows the program to modify a value of the container, but it does not allow it to read it. It is a one-way iterator. It is a write-only iterator.
3. Forward iterator:
Forward iterator uses the (++) operator to navigate through the container. Forward iterator goes through each element of a container and one element at a time.
4. Bidirectional iterator:
A bidirectional iterator is similar to a further repetition, but with additional functionality, it can move both forward and back through a container. This two-wave traversal capacity allows it to be incremented (++) and decremented (-), making it more versatile than a forward iterator.
5. Random Access Iterator:
Random access iterator can be used to access the random element of a container. Random access iterator has all the features of a bidirectional iterator, and it also has one more additional feature, i.e., pointer addition. By using the pointer addition operation, we can access the random element of a container.
There are several operations that are supported by iterators.
| iterator | Element access | Read | Write | Increment operation | Comparison |
|---|---|---|---|---|---|
| input | -> | v = *p | ++ | ==,!= | |
| output | *p = v | ++ | |||
| forward | -> | v = *p | *p = v | ++ | ==,!= |
| Bidirectional | -> | v = *p | *p = v | ++,-- | ==,!= |
| Random access | ->,[ ] | v = *p | *p = v | ++,--,+,-,+=,--= | ==,!=,<,>,<=,>= |
Lets look at an example to demonstrate iterators in C++ STL.
Output:
Input Iterator: 10 100 (Output Iterator writes 100) Forward Iterator: 99 2 3 4 Bidirectional Iterator: 15 After decrement: 10 Random Access Iterator (+2): 30 Random Access Iterator (-1): 20 Random Access Iterator with index: 30
Explanation:
This program demonstrates all types of STL iterators: input (read-only), output (write-only), forward (read/write/increment), bidirectional (supports ++, --), and random-access (+, -, [ ]). Different STL containers (vector, list, set) are used to showcase their respective iterator behaviours.
Algorithms are predefined functions in the Standard Template Library (STL), which operate on the elements of containers to process, manipulate, or analyze their contents.
STL Algorithms in C++ are divided into different categories based on their functionality and how they operate on containers.
Lets look at an example program to demonstrate algorithms in C++ STL.
Output:
Found 30 in vector Vector after reverse: 50 40 30 20 10 Vector after sorting: 10 20 30 40 50 Set union: 1 2 3 5 6 7 The sum of vector elements: 150
Explanation:
This program showcases STL algorithms: find (nonmutating), reverse (mutating), sort (sorting), set_union (set algorithm), and accumulate (relational). These functions simplify operations on containers like vectors and sets. The program performs searching, modifying, sorting, merging, and numerical operations efficiently.
A function object is also known as a 'functor'. A function object is an object that contains at least one definition of the operator() function. It means that if we declare the object 'd' of a class in which the operator() function is defined, we can use the object 'd' as a regular function.
It has the following syntax:
Lets look at an example to demonstrate Functors in C++ STL.
Output:
Vector after multiplication by 3: 3 6 9 12 15
Explanation:
This program defines a functor MultiplyBy that multiplies each element by a given factor using the operator(). The STL transform() algorithm applies the functor to all aspects of a vector, modifying them efficiently. Functors make algorithms more flexible by allowing custom operations like multiplication.
We request you to subscribe our newsletter for upcoming updates.