example1_basic_usage.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
31
#include <iostream>
#include <map>
#include <string>

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

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

    // Accessing elements
    std::cout << "Alice's age: " << age_map["Alice"] << std::endl;
    std::cout << "Bob's age: " << age_map.at("Bob") << std::endl;

    // Checking if a key exists
    if (age_map.count("David") == 0) {
        std::cout << "David is not 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;
    }

    // Size of the map
    std::cout << "Map size: " << age_map.size() << std::endl;

    return 0;
}
Back to map