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

In C++, customizing hashing and equality with std::span allows you to define how spans of data are compared and hashed. This is particularly useful when working with standard containers like std::unordered_map or std::unordered_set that require elements to be hashable.
C++, std::span, hashing, equality, customizing, C++11, data structures, unordered_map, unordered_set
// Example of customizing hashing and equality for std::span #include #include #include #include #include // A custom hash function for std::span struct SpanHasher { template std::size_t operator()(std::span s) const { std::size_t hash = 0; for (const auto& element : s) { hash ^= std::hash{}(element) + 0x9e3779b9 + (hash << 6) + (hash >> 2); } return hash; } }; // A custom equality function for std::span struct SpanEqual { template bool operator()(std::span lhs, std::span rhs) const { if (lhs.size() != rhs.size()) return false; return std::equal(lhs.begin(), lhs.end(), rhs.begin()); } }; int main() { // Create an unordered_map with std::span as key std::unordered_map<:span>, int, SpanHasher, SpanEqual> map; std::vector vec1 = {1, 2, 3}; std::vector vec2 = {4, 5, 6}; map[std::span(vec1)] = 10; map[std::span(vec2)] = 20; for (const auto& [key, value] : map) { std::cout << "Key: "; for (const auto& elem : key) { std::cout << elem << " "; } std::cout << " | Value: " << value << std::endl; } return 0; }

C++ std::span hashing equality customizing C++11 data structures unordered_map unordered_set