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

void printMultimap(const std::multimap<std::string, int>& mm) {
    for (const auto& pair : mm) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    std::cout << "Size: " << mm.size() << std::endl << std::endl;
}

int main() {
    std::multimap<std::string, int> wordCount;

    // Inserting elements
    wordCount.insert({"apple", 1});
    wordCount.insert({"banana", 2});
    wordCount.insert({"apple", 3});
    wordCount.insert({"cherry", 4});
    wordCount.insert({"banana", 5});

    std::cout << "Initial multimap:" << std::endl;
    printMultimap(wordCount);

    // Removing a single element by key
    std::string keyToRemove = "cherry";
    wordCount.erase(keyToRemove);
    std::cout << "After removing '" << keyToRemove << "':" << std::endl;
    printMultimap(wordCount);

    // Removing all elements with a specific key
    keyToRemove = "banana";
    auto removed = wordCount.erase(keyToRemove);
    std::cout << "After removing all '" << keyToRemove << "' (removed " << removed << " elements):" << std::endl;
    printMultimap(wordCount);

    // Removing a single element by iterator
    auto it = wordCount.find("apple");
    if (it != wordCount.end()) {
        wordCount.erase(it);
        std::cout << "After removing one 'apple' entry:" << std::endl;
        printMultimap(wordCount);
    }

    return 0;
}
Back to std_multimap