C++ STL — Your Super Toolbox
Unlock the full power of C++ Standard Template Library for competitive programming!
Open interactive version (quiz + challenge)Real-world analogy
What is it?
The C++ Standard Template Library (STL) is a collection of ready-made data structures and algorithms that every competitive programmer must know. It includes containers like vector, set, map, and priority_queue, plus powerful functions like sort, binary_search, and next_permutation. Mastering the STL means you write less code, make fewer bugs, and solve problems faster.
Real-world relevance
The STL mirrors tools used in real software everywhere. Google Maps uses priority queues to find shortest paths. Social media uses hash maps (unordered_map) to look up your profile in milliseconds. Online stores use sets to track unique products in your cart. Every professional C++ developer relies on the STL daily.
Key points
- Vector — The Super Array — A vector is like an array that can grow and shrink. Use push_back() to add elements at the end, pop_back() to remove the last one, size() to check how many elements, and clear() to empty it. You can also use resize() to change its size. Vectors are the most-used container in CP!
- Pair — Two Values in One Package — A pair bundles two values together, like a name tag with both first and last name. Create one with make_pair(a, b) or {a, b}, and access the values with .first and .second. Pairs are super handy for storing coordinates (x, y) or key-value data.
- Set — Unique and Sorted Automatically — A set stores unique elements and keeps them sorted at all times. Use insert() to add, erase() to remove, find() to search, and count() to check if something exists (returns 0 or 1). All operations are O(log n). Perfect for when you need unique sorted values!
- Map — Your Magic Dictionary — A map stores key-value pairs, like a real dictionary where each word (key) has a definition (value). Access values with map[key], insert with map[key] = value, and iterate through all pairs. Keys are automatically sorted, and lookup is O(log n).
- Unordered Map & Set — Lightning Speed — unordered_map and unordered_set are like map and set but use hashing instead of sorting. They don't keep elements in order, but lookups are O(1) on average — much faster! Use them when you don't need sorted order and want maximum speed.
- Priority Queue — VIP Line — A priority_queue is like a line where the biggest element always gets to go first (max-heap). To make a min-heap (smallest first), declare it as priority_queue, greater>. Push elements with push(), get the top with top(), and remove it with pop().
- Deque — Double-Ended Queue — A deque lets you add and remove from BOTH the front and the back in O(1) time. Use push_front(), push_back(), pop_front(), pop_back(). It's like a line where people can join or leave from either end. Great for sliding window problems!
- Handy STL Functions — The STL has awesome built-in functions: next_permutation gives the next arrangement, accumulate sums up a range, unique removes consecutive duplicates, __gcd finds greatest common divisor, and min/max/swap do exactly what their names say. These save tons of coding time!
- STL Tricks for CP Success — Use auto to avoid typing long type names. Range-based for loops (for (auto x : v)) make iteration clean. Sort with custom comparators using lambda functions. Combine these tricks and your CP code will be shorter, faster, and less bug-prone!
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
// SET: unique sorted elements
set<int> s = {5, 3, 1, 4, 2, 3, 1}; // duplicates removed!
s.insert(6);
cout << "Set: ";
for (int x : s) cout << x << " "; // 1 2 3 4 5 6
cout << endl;
// MAP: key-value pairs
map<string, int> score;
score["Alice"] = 95;
score["Bob"] = 87;
score["Charlie"] = 92;
cout << "Bob's score: " << score["Bob"] << endl;
// PRIORITY QUEUE (max-heap by default)
priority_queue<int> maxPQ;
maxPQ.push(30); maxPQ.push(10); maxPQ.push(50);
cout << "Max: " << maxPQ.top() << endl; // 50
// Min-heap trick
priority_queue<int, vector<int>, greater<int>> minPQ;
minPQ.push(30); minPQ.push(10); minPQ.push(50);
cout << "Min: " << minPQ.top() << endl; // 10
// USEFUL FUNCTIONS
vector<int> v = {3, 1, 4, 1, 5};
sort(v.begin(), v.end()); // 1 1 3 4 5
int total = accumulate(v.begin(), v.end(), 0); // sum = 14
cout << "Sum: " << total << endl;
// NEXT PERMUTATION
vector<int> p = {1, 2, 3};
next_permutation(p.begin(), p.end());
cout << "Next perm: ";
for (int x : p) cout << x << " "; // 1 3 2
cout << endl;
// GCD and pair
cout << "GCD(12,8): " << __gcd(12, 8) << endl; // 4
pair<int, string> hero = {100, "Coder"};
cout << hero.first << " " << hero.second << endl;
return 0;
}Line-by-line walkthrough
- 1. We include bits/stdc++.h which gives us access to ALL STL containers and algorithms — one include to rule them all!
- 2. We create a set with some duplicate values. The set automatically removes duplicates and sorts: {5,3,1,4,2,3,1} becomes {1,2,3,4,5}. We insert 6, and it goes to the right spot.
- 3. We iterate through the set with a range-based for loop. Elements come out in sorted order: 1 2 3 4 5 6.
- 4. We create a map from strings to ints for storing scores. Assigning score['Alice'] = 95 creates the entry. Accessing score['Bob'] returns 87.
- 5. We create a max-heap priority_queue. After pushing 30, 10, 50, calling top() gives us 50 — the maximum element.
- 6. For a min-heap, we use the longer declaration with greater. Now top() gives 10 — the minimum. This is a super common CP trick!
- 7. We use accumulate() to sum up a sorted vector. It takes begin, end, and an initial value (0). The result is the total sum: 14.
- 8. next_permutation rearranges {1,2,3} to the next lexicographic permutation: {1,3,2}. Call it repeatedly to generate all permutations!
- 9. __gcd(12, 8) computes the greatest common divisor, returning 4. A pair bundles two values — here an int and a string.
- 10. Every one of these tools is something you'd otherwise have to code from scratch. The STL gives them to you for free — learn them and you'll code faster in every contest!
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
map<string, int> freq;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string word;
cin >> word;
freq[word]++;
}
// Print words that appear more than once
for (auto it = freq.begin(); it != freq.end(); it++) {
if (it.second > 1) {
cout << it.first << ": " << it.second << endl;
}
}
return 0;
}Need a hint?
Show answer
Explain like I'm 5
Fun fact
Hands-on challenge
More resources
- C++ STL Cheat Sheet (cplusplus.com)
- STL in C++ for Competitive Programming (YouTube)
- HackerRank STL Practice (HackerRank)