example3_map_associative_container.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
28
29
30
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages;

    // Inserting key-value pairs
    ages["Alice"] = 30;
    ages["Bob"] = 25;
    ages.insert({"Charlie", 35});

    // Accessing and modifying values
    ages["Bob"] = 26;

    // Checking if a key exists
    if (ages.count("David") == 0) {
        std::cout << "David is not in the map" << std::endl;
    }

    // Iterating through the map
    for (const auto& [name, age] : ages) {
        std::cout << name << " is " << age << " years old." << std::endl;
    }

    // Erasing an element
    ages.erase("Charlie");

    return 0;
}
Back to containers