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

// Custom comparator for pair<int, string>
struct PairCompare {
    bool operator()(const std::pair<int, std::string>& lhs, 
                    const std::pair<int, std::string>& rhs) const {
        if (lhs.first != rhs.first)
            return lhs.first < rhs.first;
        return lhs.second < rhs.second;
    }
};

int main() {
    std::map<std::pair<int, std::string>, double, PairCompare> scores;

    scores[{1, "Alice"}] = 95.5;
    scores[{2, "Bob"}] = 89.0;
    scores[{1, "Charlie"}] = 91.5;
    scores[{3, "David"}] = 87.5;

    for (const auto& entry : scores) {
        std::cout << "Student ID: " << entry.first.first 
                  << ", Name: " << entry.first.second 
                  << ", Score: " << entry.second << std::endl;
    }

    // Finding a specific entry
    auto it = scores.find({1, "Alice"});
    if (it != scores.end()) {
        std::cout << "\nFound: " << it->first.second 
                  << " (ID: " << it->first.first 
                  << ") with score " << it->second << std::endl;
    }

    return 0;
}
Back to map