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

// Custom comparator for case-insensitive string comparison
struct CaseInsensitiveCompare {
    bool operator()(const std::string& a, const std::string& b) const {
        return std::lexicographical_compare(
            a.begin(), a.end(), b.begin(), b.end(),
            [](char c1, char c2) { return std::tolower(c1) < std::tolower(c2); }
        );
    }
};

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

    scores["Alice"] = 100;
    scores["bob"] = 85;
    scores["CHARLIE"] = 90;

    // This will update "Alice" instead of creating a new entry
    scores["aLiCe"] = 95;

    for (const auto& pair : scores) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
Back to map