Standard Template Library (STL)

⚡ C++ Lesson 14 Advanced

The Standard Template Library (STL) provides a collection of generic algorithms and data structures (containers) to handle lists, sets, and key-value maps.

1 STL Containers: vector, set, and map

Common containers inside the STL library include:

  • std::vector: A dynamically resizing, contiguous sequence container.
  • std::set: Stores unique values sorted automatically. Excellent for validation checks.
  • std::map: Stores key-value pairings (e.g. username mapped to high scores) sorted by key.
2 STL Operations Code

Let's run a program utilizing vector, set, and map operations:

C++ — STL Containers ▶ Run Code
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <string>

int main() {
    // 1. Vector (List)
    std::vector<std::string> items = {"Apple", "Banana"};
    items.push_back("Apple"); // Duplicates allowed

    // 2. Set (Unique items only)
    std::set<int> uniqueNums = {10, 20, 10}; // Second 10 is ignored
    
    // 3. Map (Key-Value pairs)
    std::map<std::string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"] = 88;

    std::cout << "Set size: " << uniqueNums.size() << "\n";
    std::cout << "Alice's Score: " << scores["Alice"] << "\n";

    return 0;
}
3 Code Challenge
Challenge: Write a program that declares a `std::map` mapping product names (strings) to prices (doubles). Add three items, look up the price of one item, and print the retrieved price.