C++ STL Tutorial: From Theory to Practical
Did you know that C++ has entered the top three programming languages around the globe with a market share of 17.53 percent? One of the reasons behind popularity of C++ is its built-in standard template library, commonly referred to as C++ STL, which offers a variety of templates for containers, algorithms, iterators, and function objects.
STL is preferred by many developers globally as it provides its users with a way to develop generic and reusable code. It means that you do not need to develop unique pieces of code for every type of data and algorithm you wish to use in your code. In this blog, we will understand STL, its various components, and its benefits in writing codes.
What is C++ STL?
The C++ Standard Template Library is a collection of template classes in C++. It provides several programming functions as well as data structures such as Lists, Arrays, Stacks, etc.
The data structures and algorithms contained in C++ standard template library are used to streamline the creation of C++ programs. You can find various containers for the purpose of data searching, sorting, as well as manipulation in the standard template library offered by C++.
The standard template library also allows you to create effective codes in C++. Most of the data structures stored in STL are implemented with the help of optimized algorithms. This saves users a lot of time used by performing quick execution of your written codes in C++.
If you want to build a strong foundation in programming, you can enroll in a C and C++ course.
Components of C++ STL
By now, we have understood that STL makes your program robust as well as reusable. It will also assist you in object storage and manipulation. Next, let’s study various components inside C++ standard template library. It is essentially composed of four main components. These are:
- Containers
- Iterators
- Algorithms
- Function Objects
Containers
While developing code for your application, if you are dealing with a lot of different elements, you should probably consider using any type of container. A container is simply referred to as an object, which can be used to store a whole collection of data. A container will help you to effectively recreate and put into use some complex data structures. Furthermore, containers can be classified into three major categories. These are:
- Associative Containers- These are the types of containers in which every element that’s present inside will have a value particularly related to a key.
- Sequence Containers- Such containers are essentially required to implement linked lists, arrays, and other sequential data structures in your program. These types of containers are used to implement maps, sets, multisets, etc.
- Container Adapters- A container adapter is referred to as an interface, which can add functionality to the already existing or built containers by you.
Example:
In the below example, we will use the vector class to show how a sequential container operates in C++ standard template library.
#include <iostream>
#include <vector>
int main() {
// initialize a vector of int type
std::vector<int> numbers = {10, 300, 15, 60, 130};
// print the numbers in the vector
std::cout << "Numbers are: ";
for(const auto&num: numbers) {
std::cout << num << ", ";
}
std::cout << std::endl;
return 0;
}
OUTPUT
Numbers are: 10, 300, 15, 60, 130.
Iterators
C++ STL is used to navigate through the container elements. The iterators can also be used to access the data stored within these containers. They can further be used to manipulate data elements in a container. An iterator can be incremented or decremented as per your desire. The following are a couple of Iterator functions:
- begin() – By using begin() function in STL, you can direct the iterator to the first element stored in the container.
- end() – The end() function in STL is used to direct the iterator to the final element present inside the container.
Example:
The following code illustrates the conceptual meaning of iterators in C++ STL.
#include <iostream>
#include <vector>
int main()
{
// initialize a vector
std::vector<int> v1 = { 10, 30, 17, 45};
// declare an iterator
std::vector<int>::iterator itr;
// access vector elements without iterator
std::cout << "Traversing without iterator : ";
for (int j = 0; j < 4; ++j) {
std::cout << v1[j] << " ";
}
std::cout << "\n";
// access vector elements using an iterator
std::cout << "Traversing using iterator ";
for (itr = value.begin(); itr != v1.end(); ++itr) {
std::cout << *itr << " ";
}
std::cout << std::endl << std::endl;
// insert an element into the vector
value.push_back(99);
// access vector elements without iterator
cout << "Traversing without iterator : ";
for (int j = 0; j < 5; ++j) {
std::cout << values[j] << " ";
}
std::cout << std::endl;
// access vector elements using an iterator
std::cout << "Traversing using iterator ";
for (itr = values.begin(); itr != values.end(); ++itr) {
std::cout << *itr << " ";
}
std::cout << std::endl << std::endl;
return 0;
}
Output:
Traversing without iterator: 10 30 17 45
Traversing using iterator: 10 30 17 45
Modified vector: 10 30 17 45 99
Algorithms
As we studied Iterators, it is important to note that iterators in STL can be used to implement various algorithms of all kinds in C++. Algorithms are referred to as functions, which are applied to containers. The algorithms provide the functionality to the elements stored in a container inside C++ STL.
For example, sort(), min(), swap(), and max() are a few algorithms available in C++ standard template library.
Example:
To implement the code of binary search in C++, we need to write the following function.
bool binary_search( int l , int r , int key ,int a[])
{
if(l > r)
return false;
else
{
int mid=(l+r)/2;
if(a[mid] == key)
{
return true;
}
else if(a[mid] > key) {
return binary_search(l, mid-1, key, a);
}
else if(a[mid] < key)
{
return binary_search(l, mid+1, -1, key, a);
else if (a[mid] < key) {
return binary_search(mid + 1, r, key, a);
}
}
}
In STL, we can easily make use of the algorithm binary search() function in the library to perform the binary search. The C++ standard template library already contains a definition for it.
Function Objects
An object of a class that offers a definition to an operator() is referred to as a function object or a functor. Assuming you have declared an object of a certain class, you can now use it in the same way as a function.
Example:
Below is a program to execute the sorting of an array in ascending order using C++ STL.
#include<iostream>
#include<functional>
#include<algorithm>
int main(){
// Function Objects (Functor) : A function wrapped in a class so that it is available like an object
int arr[] = {7, 23, 46, 5, 64, 9};
std::sort(arr,arr+5);
for (int i = 0; i < 5; i++)
{
std::cout<<arr[i]<<endl;
}
return 0;
}
Output:
5792346
Advantages of C++ STL
The Standard Template Library in C++ has the following benefits:
- Reusability- It offers a way to develop generic, reusable codes that can be used with various data types. This characteristic results in more maintainable and effective code writing.
- Effective Algorithms- These include many data structures and algorithms that can be easily implemented with the help of optimized codes. This feature leads to quicker execution times than custom code.
- Enhanced Readability- It offers a standardized and well-documented method of dealing with data. It makes your code simple to comprehend.
- Large User-base- There is a sizable developer community behind C++ STL as it is so widely used. The community and user base offer assistance and resources like tutorials and discussion boards.
Conclusion
In this blog, we discussed C++ STL in detail, along with its components such as containers, iterators, algorithms, and function objects with the help of sample codes. We also discussed the advantages offered by STL which makes it a reliable and popular choice among developers.