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

In C++, customizing hashing and equality for std::array is essential for using them in associative containers like std::unordered_map and std::unordered_set. By default, std::array does not provide a hash function, so you'll need to implement your own.

To customize hashing, you can create a struct that overloads the operator() to compute a hash value based on the contents of the std::array. For equality comparison, you can implement another operator overload to handle that as well.

#include <array> #include <iostream> #include <functional> template <typename T, std::size_t N> struct ArrayHash { std::size_t operator()(const std::array<T, N>& arr) const { std::size_t seed = 0; for (const auto& elem : arr) { seed ^= std::hash<T>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; template <typename T, std::size_t N> struct ArrayEqual { bool operator()(const std::array<T, N>& lhs, const std::array<T, N>& rhs) const { return lhs == rhs; } }; int main() { std::array<int, 3> a = {1, 2, 3}; std::array<int, 3> b = {1, 2, 3}; ArrayHash<int, 3> hashFunc; ArrayEqual<int, 3> equalFunc; std::cout << "Hash of a: " << hashFunc(a) << std::endl; std::cout << "a equals b: " << equalFunc(a, b) << std::endl; return 0; }

C++ std::array hashing equality custom hash function associative containers