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

In C++, you can customize hashing and equality checks when using std::unordered_set by providing your own hash function and equality comparator. This allows you to store complex objects in unordered sets while controlling how they are hashed and compared for equality.

Custom Hash Function

A custom hash function needs to be defined for the type you want to store in std::unordered_set. You can create a struct that overloads the () operator.

Custom Equality Function

Similarly, a custom equality function can be created using a struct that also overloads the () operator.

Example

#include <iostream> #include <unordered_set> struct Person { std::string name; int age; // Equality operator bool operator==(const Person& other) const { return (name == other.name && age == other.age); } }; // Custom hash function struct PersonHash { std::size_t operator()(const Person& p) const { return std::hash<:string>()(p.name) ^ std::hash()(p.age); } }; int main() { std::unordered_set people; people.insert({"Alice", 30}); people.insert({"Bob", 25}); for (const auto& person : people) { std::cout << person.name << " is " << person.age << " years old." << std::endl; } return 0; }

C++ unordered_set custom hashing equal function C++ data structures