STL stands for C++ Standard Template Library. It is a set of C++ template classes.
STL provides us with the implementation of complex data structures and algorithms which reduces our code size and makes our code more readable.
For example, If we want to use a stack data structure, we don't have to implement it ourselves but we can use the inbuilt stack container i.e stack<int> s. It is a library that contains containers, iterators, algorithms, and functors. Let's get an overview of each one by one.
Containers
Containers are implemented data structures that store data and objects. For example, vector, stack, linked list. They are generic i.e they can hold the value of any data type. Containers can be of four types:
- Sequential: Stores data in contiguous memory locations. Example: vector, stack, queue.
- Ordered: Stores data in sorted form. Example: map, multimap, multiset.
- Unordered: Stores data unorderly. Example: unordered_map, unordered_set.
- Nested: Containers inside containers. Example:
vector<vector<int>> v; // vector inside a vector
Iterators
Iterators are similar to pointers but they are implemented to point memory addresses of STL containers. Iterators are a bridge between containers and algorithms. They also provide us with abstraction i.e we can use the algorithm without having to worry about the implementation. An iterator is defined for a vector below:
vector<int> iterator::itr;Algorithms
Algorithms are a very important part of C++ STL. They allow us to perform operations on containers. For example, the sort() function is used to perform sorting operations on containers. Algorithms help us perform complex operations on containers easily.
Functors
Functors are also called function objects. Functors are classes that can be used as a function. They are classes declared with () operator overloaded.
struct func {
void operator()(int x) // This is a functor
{
cout << x << endl;
}
}; Applications of STL:
- STL reduces our efforts of implementing data structures and algorithms from scratch.
- It provides abstraction.
- Reduces the code size.
- It is reliable and fast.
- It prevents us from reinventing the wheel, and focusing on the use-case without worrying about the implementation.
- It is well tested and optimized and thus provides us with the most optimized approach for a particular function.
- Different containers of STL are used in different problems, for example, if we want to store the frequency of characters, a hashmap is to be used.