example2_custom_hash.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
#include <iostream>
#include <unordered_map>
#include <string>

struct Person {
    std::string firstName;
    std::string lastName;

    bool operator==(const Person& other) const {
        return firstName == other.firstName && lastName == other.lastName;
    }
};

// Custom hash function for Person
struct PersonHash {
    std::size_t operator()(const Person& p) const {
        return std::hash<std::string>()(p.firstName) ^ std::hash<std::string>()(p.lastName);
    }
};

int main() {
    std::unordered_map<Person, int, PersonHash> personAgeMap;

    // Insertion
    personAgeMap[{"Alice", "Smith"}] = 30;
    personAgeMap[{"Bob", "Brown"}] = 25;

    // Lookup
    Person searchPerson = {"Alice", "Smith"};
    if (personAgeMap.find(searchPerson) != personAgeMap.end()) {
        std::cout << "Found Alice Smith, age: " << personAgeMap[searchPerson] << std::endl;
    }

    return 0;
}
Back to std_unordered_map