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

int main() {
    std::multiset<std::string> words = {
        "apple", "banana", "cherry", "date", "apple", "fig",
        "grape", "apple", "banana", "elderberry"
    };

    // Count frequency of each word
    std::map<std::string, int> frequency;
    for (const auto& word : words) {
        frequency[word]++;
    }

    // Print frequency
    std::cout << "Word frequencies:" << std::endl;
    for (const auto& pair : frequency) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    // Remove all instances of a specific word
    std::string word_to_remove = "apple";
    auto removed = words.erase(word_to_remove);
    std::cout << "\nRemoved " << removed << " instance(s) of '" << word_to_remove << "'" << std::endl;

    // Print remaining words
    std::cout << "\nRemaining words:" << std::endl;
    for (const auto& word : words) {
        std::cout << word << " ";
    }
    std::cout << std::endl;

    return 0;
}
Back to std_multiset