ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 7 min read

The Standard Template Library (STL): Containers & Iterators

std::vector, std::unordered_map, std::deque, and range-based for loops

The Standard Template Library (STL) provides high-performance generic algorithms, iterators, and container data structures.

Key STL Containers

std::vector<T>: Dynamic contiguous array. The default container for 95% of use cases in modern C++.

std::unordered_map<Key, Value>: Hash table with average O(1) key lookups.

std::map<Key, Value>: Red-Black tree maintaining keys in sorted order (O(log n) lookups).

Iterators: Generalization of pointers enabling algorithms to traverse containers independently of their underlying implementation.

Using std::vector and std::unordered_map
#include <iostream>
#include <vector>
#include <unordered_map>

int main() {
    // Dynamic vector with push_back and emplace_back
    std::vector<int> numbers = {10, 20, 30};
    numbers.push_back(40);

    // Range-based for loop
    for (const auto &n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    // Fast hash map
    std::unordered_map<std::string, double> coursePrices;
    coursePrices["C++ Systems"] = 49.99;
    coursePrices["Rust Engine"] = 59.99;

    std::cout << "Price: $" << coursePrices["C++ Systems"] << std::endl;
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which STL container stores elements in contiguous memory and should be your default choice in C++?