To customize hashing and equality in std::unordered_map
, you can define your own hash function and equality predicate. This is particularly useful when you need to store complex objects as keys in the map.
Below is an example where we create a custom struct and define a hash function and equality operator for it:
#include <iostream>
#include <unordered_map>
struct Point {
int x, y;
// Equality operator
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
// Custom hash function
struct PointHash {
std::size_t operator()(const Point& point) const {
return std::hash()(point.x) ^ std::hash()(point.y);
}
};
int main() {
// Create an unordered_map with custom key type and hash function
std::unordered_map pointMap;
pointMap[{1, 2}] = "Point A";
pointMap[{3, 4}] = "Point B";
// Accessing value using custom key
std::cout << pointMap[{1, 2}] << std::endl; // Output: Point A
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?