Learn how to customize hashing and equality comparisons for std::vector in C++. This guide provides examples and explanations to help you implement your own hashing functions and equality operators.
custom hashing, equality comparison, std::vector, C++, programming, data structures
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
struct VectorHasher {
std::size_t operator()(const std::vector& vec) const {
std::size_t hash = 0;
for (const auto& item : vec) {
hash ^= std::hash()(item) + 0x9e3779b9 + (hash << 6) + (hash >>> 2);
}
return hash;
}
};
struct VectorEqual {
bool operator()(const std::vector& lhs, const std::vector& rhs) const {
return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
};
int main() {
std::unordered_map<:vector>, std::string, VectorHasher, VectorEqual> myMap;
myMap[{1, 2, 3}] = "First";
myMap[{4, 5, 6}] = "Second";
for (const auto& pair : myMap) {
std::cout << "Key: ";
for (int num : pair.first) {
std::cout << num << " ";
}
std::cout << " - Value: " << pair.second << 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?