example4_operations_modifications.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <map>
#include <string>

void printMap(const std::map<std::string, int>& m) {
    for (const auto& pair : m) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    std::cout << std::endl;
}

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

    // Inserting elements
    inventory["apple"] = 5;
    inventory["banana"] = 8;
    inventory["orange"] = 10;

    std::cout << "Initial inventory:" << std::endl;
    printMap(inventory);

    // Modifying an element
    inventory["apple"] = 7;

    // Erasing an element
    inventory.erase("orange");

    std::cout << "After modifications:" << std::endl;
    printMap(inventory);

    // Finding an element
    auto it = inventory.find("banana");
    if (it != inventory.end()) {
        std::cout << "Found " << it->first << " with quantity " << it->second << std::endl;
    }

    // Inserting with hint
    auto hint = inventory.lower_bound("cherry");
    inventory.insert(hint, {"cherry", 15});

    std::cout << "After inserting cherry:" << std::endl;
    printMap(inventory);

    // Using emplace
    inventory.emplace("grape", 20);

    std::cout << "Final inventory:" << std::endl;
    printMap(inventory);

    return 0;
}
Back to map