C++ STL Tutorial
In the previous chapters, we have learned about the concept of C++ templates. The C++ STL (Standard Template Library) is a powerful set of C++ template classes that provide generic template classes and functions, which can implement various popular and commonly used algorithms and data structures, such as vectors, lists, queues, and stacks.
The core of the C++ Standard Template Library includes the following three components:
Component | Description |
---|---|
Containers | Containers are used to manage collections of a certain type of object. C++ provides various types of containers, such as deque, list, vector, map, etc. |
Algorithms | Algorithms operate on containers. They provide ways to perform various operations, including initializing, sorting, searching, and transforming the contents of containers. |
Iterators | Iterators are used to traverse the elements of a collection. These collections can be containers or subsets of containers. |
These three components come with rich predefined functions, helping us handle complex tasks in a simple way.
The following program demonstrates the vector container (a standard C++ template), which is very similar to an array, with the only difference being that the vector automatically handles its storage needs when the size needs to be extended:
Example
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create a vector to store int
vector<int> vec;
int i;
// Display the original size of vec
cout << "vector size = " << vec.size() << endl;
// Push 5 values into the vector
for(i = 0; i < 5; i++){
vec.push_back(i);
}
// Display the extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// Access 5 values in the vector
for(i = 0; i < 5; i++){
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// Use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
A few points to note about the various functions used in the above example:
- The
push_back()
member function inserts values at the end of the vector, expanding the vector size if necessary. - The
size()
function displays the size of the vector. - The
begin()
function returns an iterator pointing to the beginning of the vector. - The
end()
function returns an iterator pointing to the end of the vector.