The Standard Template Library (STL) is one of the most powerful tools in C++. It provides a collection of ready-to-use classes and functions for data structures and algorithms, making your code efficient and clean.
In this blog, we’ll explore the most used STL components: vector, map, set, and pair, with clear examples and outputs.
Introduction to STL in C++: Mastering Vectors, Maps, Sets, and Pairs
What is STL?
STL stands for Standard Template Library. It provides:
-
Containers: Like
vector
,map
,set
, etc. -
Algorithms: Like
sort()
,find()
,count()
, etc. -
Iterators: To traverse containers.
1. Vector in C++
A vector
is a dynamic array that can grow and shrink during runtime.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums={10, 20, 30}; nums.push_back(40); for(int i=0;i<nums.size();i++) { cout<<nums[i]<<" "; } return 0; }
Output: 10 20 30 40
2. Map in C++
A map
is a container that stores key-value pairs in sorted order by key.
#include <iostream> #include <map> using namespace std; int main() { map<string,int>age; age["Alice"]=25; age["Bob"]=30; for(auto it:age) { cout<<it.first<<": "<<it.second<<endl; } return 0; }
Output: Alice: 25 Bob: 30
3. Set in C++
A set
stores unique elements in sorted order. Duplicates are automatically removed.
#include <iostream> #include <set> using namespace std; int main() { set<int> s; s.insert(10); s.insert(5); s.insert(10); // Duplicate won't be added for(auto val:s){ cout<<val<< " "; } return 0; }
Output: 5 10
4. Pair in C++
A pair
is a simple container to store two related values.
#include <iostream> using namespace std; int main() { pair<string,int> p; p=make_pair("CodeSpeedy", 2025); cout<<p.first<<" "<<p.second<<endl; return 0; }
Output: CodeSpeedy 2025