example1_unordered_map.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> age_map;

    // Inserting elements
    age_map["Alice"] = 30;
    age_map["Bob"] = 25;
    age_map.insert({"Charlie", 35});

    // Accessing elements
    std::cout << "Alice's age: " << age_map["Alice"] << std::endl;

    // Checking if a key exists
    if (age_map.find("David") == age_map.end()) {
        std::cout << "David not found in the map" << std::endl;
    }

    // Iterating through the map
    for (const auto& pair : age_map) {
        std::cout << pair.first << " is " << pair.second << " years old" << std::endl;
    }

    return 0;
}
Back to unordered_map