C++C++ · Lesson 6 of 9

STL Containers

The Standard Template Library is C++'s collection of containers and algorithms. It's massive, powerful, and the reason you don't have to implement your own linked list.

C++
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <numeric>
using namespace std;

int main() {
    // vector — dynamic array
    vector<int> v = {5, 2, 8, 1, 9, 3};
    sort(v.begin(), v.end());
    cout << "Sorted: ";
    for (int n : v) cout << n << " ";
    cout << "
";  // 1 2 3 5 8 9

    int total = accumulate(v.begin(), v.end(), 0);
    cout << "Sum: " << total << "
";  // 28

    auto it = find(v.begin(), v.end(), 5);
    cout << "5 found: " << (it != v.end()) << "
";  // 1 (true)

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

    for (const auto& [name, score] : scores) {
        cout << name << ": " << score << "
";  // alphabetical order
    }

    // unordered_map — hash table, O(1) lookup, no order
    unordered_map<string, int> fast_scores = {
        {"Alice", 95}, {"Bob", 87}
    };

    // set — sorted unique elements
    set<int> unique = {5, 3, 1, 4, 1, 5, 9, 2, 6};  // duplicates removed
    cout << "Set: ";
    for (int n : unique) cout << n << " ";  // 1 2 3 4 5 6 9
    cout << "
";

    return 0;
}
◆ Note
Use vector for most things. Use map when you need sorted iteration or don't care about lookup speed. Use unordered_map when you need fast (O(1)) lookup and don't care about order. Use set for unique sorted collections.