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.
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.
Similarly, a custom equality function can be created using a struct that also overloads the ()
operator.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?