Lesson 50 of 50 intermediate

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

The STL is like a super workshop full of perfectly-built tools. Instead of making your own hammer (array), you grab a vector — it's a hammer that grows when you need more nails! Need to look up a word? Use a map — it's like a magical dictionary that finds any word instantly. A set is like a jar that only keeps unique marbles and sorts them automatically. A priority_queue is like a line where the tallest person always goes first. Once you learn what each tool does, you'll solve problems 10x faster!

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

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. 1. We include bits/stdc++.h which gives us access to ALL STL containers and algorithms — one include to rule them all!
  2. 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. 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. 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. 5. We create a max-heap priority_queue. After pushing 30, 10, 50, calling top() gives us 50 — the maximum element.
  6. 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. 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. 8. next_permutation rearranges {1,2,3} to the next lexicographic permutation: {1,3,2}. Call it repeatedly to generate all permutations!
  9. 9. __gcd(12, 8) computes the greatest common divisor, returning 4. A pair bundles two values — here an int and a string.
  10. 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?
Look closely at how we access the iterator's members. Map iterators are pointers to pairs — how do you access members of a pointer?
Show answer
The bug is using it.second and it.first instead of it->second and it->first. Since 'it' is an iterator (acts like a pointer), you must use the arrow operator (->) to access pair members, not the dot operator (.). Alternatively, you could use (*it).second. Fix both lines to use it->first and it->second and the code works perfectly!

Explain like I'm 5

Imagine you have a super toy box with special compartments. One compartment is a magic bag (vector) that gets bigger whenever you put more toys in it. Another is a special jar (set) that only keeps one of each kind of marble and lines them up by size automatically. There's a magic notebook (map) where you write a friend's name and it instantly tells you their favorite color. And there's a special slide (priority queue) where the biggest kid always goes down first. With all these amazing compartments, you can organize anything super fast without building your own boxes from scratch!

Fun fact

The C++ STL was designed by Alexander Stepanov, who spent over 20 years thinking about generic programming before the STL was accepted into C++ in 1994. He believed algorithms should be written once and work with any data type — and that's exactly what templates let you do!

Hands-on challenge

Write a program that reads n words from input, counts how many times each word appears using a map, then prints the words and their counts sorted by frequency (highest first). Hint: Use a map to count, transfer to a vector of pairs, then sort with a custom comparator!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero