Introduction to STL
What is STL?
The Standard Template Library (STL) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks. STL has four components:
- Algorithms
- Containers
- Functions
- Iterators
Containers
Containers are objects that store data. STL provides several types of containers:
- Sequence Containers: These store data in a linear sequence. Examples include
vector
,deque
,list
. - Associative Containers: These store data in a sorted order. Examples include
set
,map
,multiset
,multimap
. - Derived Containers: These are containers with real-world modeling. Examples include
stack
,queue
,priority_queue
.
Iterators
Iterators are used to point at the memory addresses of STL containers. They are used to iterate over container elements. Some important iterator types include:
- Input Iterators: Used to read values from a sequence.
- Output Iterators: Used to write values to a sequence.
- Forward Iterators: Can be read and written to in a forward direction.
- Bidirectional Iterators: Can be read and written to in both forward and backward directions.
- Random Access Iterators: Can be read and written to and can jump to any element.
Algorithms
Algorithms are a set of instructions applied to the data structures to perform operations like searching, sorting, etc. STL provides many algorithms, such as:
sort
reverse
copy
find
binary_search
Example: Using a Vector
Below is an example of how to use a vector
in C++:
#include <iostream> #include <vector> int main() { std::vector<int> vec; // Adding elements to vector vec.push_back(1); vec.push_back(2); vec.push_back(3); // Displaying elements of vector for(int i = 0; i < vec.size(); i++) { std::cout << vec[i] << " "; } return 0; }
Example: Using a Map
Below is an example of how to use a map
in C++:
#include <iostream> #include <map> int main() { std::map<std::string, int> map; // Adding elements to map map["one"] = 1; map["two"] = 2; map["three"] = 3; // Displaying elements of map for(const auto &pair : map) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }
one: 1
two: 2
three: 3