C++ STL

The C++ STL (Standard Template Library) is a collection of ready-made containers, iterators and algorithms. Learning the STL saves you from writing your own lists, sorting routines and lookup tables.

Common STL Containers

  • vector: dynamic array, the default choice
  • map: sorted key-value pairs
  • unordered_map: hash table with fast average lookups
  • set / unordered_set: unique values
  • deque, list, stack, queue, priority_queue: special-purpose containers

std::map and Structured Bindings

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> stock{{"rice", 40}, {"tea", 15}};
    stock["oil"] = 22;
    stock["tea"] += 5;

    for (const auto& [item, qty] : stock)
        std::cout << item << ": " << qty << '\n';

    std::cout << std::boolalpha << stock.contains("sugar") << '\n';
}
oil: 22
rice: 40
tea: 20
false

STL Algorithms

The <algorithm> header has dozens of algorithms. C++20 ranges versions accept the whole container instead of begin/end pairs.

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{5, 2, 9, 1, 7};
    std::ranges::sort(v);
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';

    auto big = std::ranges::count_if(v, [](int x) { return x > 4; });
    std::cout << "Greater than 4: " << big << '\n';

    auto it = std::ranges::find(v, 9);
    std::cout << "9 found at index " << (it - v.begin()) << '\n';
}
1 2 5 7 9
Greater than 4: 3
9 found at index 4

std::set for Unique Values

#include <iostream>
#include <set>

int main() {
    std::set<int> ids{4, 1, 4, 3, 1};
    ids.insert(2);
    for (int id : ids) std::cout << id << ' ';
    std::cout << "(" << ids.size() << " unique)\n";
}
1 2 3 4 (4 unique)

Frequently asked questions

What is the difference between map and unordered_map in C++?

std::map keeps keys sorted and has O(log n) operations. std::unordered_map uses hashing for average O(1) lookups but has no order. Use unordered_map for speed when order does not matter.

What are iterators in C++?

Iterators are objects that point to elements in a container and can move through them, like generalized pointers. Algorithms use them to work with any container.

How do I sort a vector in C++?

Use std::sort(v.begin(), v.end()) or, in C++20, std::ranges::sort(v). Pass a comparison like std::greater{} to sort in descending order.