In C++, heterogeneous lookup using `std::unordered_map` allows for more flexibility in key types by leveraging type erasure to access different types of keys using a consistent interface. This means you can easily look up or access values associated with keys of different types.
Here’s a simple example demonstrating heterogeneous lookup with `std::unordered_map`:
#include <iostream>
#include <unordered_map>
#include <string>
#include <variant>
using KeyType = std::variant<int, std::string>;
struct KeyHasher {
std::size_t operator()(const KeyType& key) const {
return std::visit([](const auto& k) { return std::hash<std::decay_t<decltype(k)>>{}(k); }, key);
}
};
struct KeyEqual {
bool operator()(const KeyType& lhs, const KeyType& rhs) const {
return lhs == rhs;
}
};
int main() {
std::unordered_map<KeyType, std::string, KeyHasher, KeyEqual> my_map;
// Insert values
my_map[42] = "Answer to life";
my_map[std::string("hello")] = "Greeting";
// Access values
std::cout << std::get<std::string>(my_map[std::string("hello")]) << std::endl; // Output: Greeting
std::cout << my_map[42] << std::endl; // Output: Answer to life
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?