// 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;
}
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?