How do I customize hashing and equality with std::set?

C++, std::set, custom hashing, equality operator, unordered_set, programming, data structures
This article explores how to customize hashing and equality checks in C++ using the std::set container. Learn how to implement your own hash functions and equality operators for custom objects.
#include <iostream>
#include <string>
#include <set>

// Custom object
struct Person {
    std::string name;
    int age;

    // Operator to compare two Person objects
    bool operator<(const Person& other) const {
        return name < other.name; // Customize comparison based on name
    }
};

// Custom hash function
struct PersonHash {
    std::size_t operator()(const Person& person) const {
        return std::hash<std::string>()(person.name); // Hash based on name
    }
};

// Custom equality operator
struct PersonEqual {
    bool operator()(const Person& lhs, const Person& rhs) const {
        return lhs.name == rhs.name && lhs.age == rhs.age; // Check equality by name and age
    }
};

int main() {
    // Create a set of Person
    std::set<Person> people;
    people.insert({"Alice", 30});
    people.insert({"Bob", 25});
    // Print people
    for (const auto& person : people) {
        std::cout << person.name << " is " << person.age << " years old." << std::endl;
    }
    return 0;
}
    

C++ std::set custom hashing equality operator unordered_set programming data structures