STL

STL Containers

Use the Standard Template Library's powerful containers: vector, map, set, and more.

Standard Template Library

The STL provides generic, reusable data structures and algorithms. Key containers:

  • vector — dynamic array
  • list — doubly-linked list
  • deque — double-ended queue
  • map — key-value pairs (sorted, BST)
  • unordered_map — key-value pairs (hash table, faster)
  • set — unique values (sorted)
  • unordered_set — unique values (hash table)
  • stack / queue / priority_queue

Iterators

All STL containers provide iterators for traversal. Use range-based for loops for simplicity.

Example

cpp
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
using namespace std;

int main() {
    // vector - dynamic array
    vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
    nums.push_back(5);
    nums.pop_back();

    sort(nums.begin(), nums.end());

    for (int n : nums) cout << n << " ";
    cout << endl;

    // auto with iterators
    auto it = find(nums.begin(), nums.end(), 4);
    if (it != nums.end()) cout << "Found 4!" << endl;

    // map - sorted key-value pairs
    map<string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"] = 87;
    scores["Charlie"] = 92;

    for (const auto& [name, score] : scores) {  // C++17 structured bindings
        cout << name << ": " << score << endl;
    }

    // unordered_map - hash map (faster lookups)
    unordered_map<string, string> capitals;
    capitals["France"] = "Paris";
    capitals["Japan"] = "Tokyo";

    if (capitals.count("France")) {
        cout << "France capital: " << capitals["France"] << endl;
    }

    // set - unique sorted values
    set<int> unique_nums = {3, 1, 4, 1, 5, 9, 2, 6, 5};
    cout << "Unique count: " << unique_nums.size() << endl;  // 7

    // STL algorithms
    vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int sum = 0;
    for_each(v.begin(), v.end(), [&sum](int n) { sum += n; });
    cout << "Sum: " << sum << endl;

    auto evens = count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; });
    cout << "Even count: " << evens << endl;

    return 0;
}
Try it yourself — CPP