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

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

    // Inserting multiple values for the same key
    grades.insert({"Alice", 85});
    grades.insert({"Bob", 90});
    grades.insert({"Alice", 92});
    grades.insert({"Charlie", 88});
    grades.insert({"Bob", 95});

    // Printing all entries
    for (const auto& grade : grades) {
        std::cout << grade.first << ": " << grade.second << std::endl;
    }

    // Finding all grades for a specific student
    std::string student = "Bob";
    auto range = grades.equal_range(student);
    std::cout << "\nGrades for " << student << ":" << std::endl;
    for (auto it = range.first; it != range.second; ++it) {
        std::cout << it->second << std::endl;
    }

    // Counting entries for a key
    std::cout << "\nNumber of grades for Alice: " << grades.count("Alice") << std::endl;

    return 0;
}
Back to map