Middle+
Co je třeba udělat, aby bylo možné použít vaši třídu jako klíč v mapě nebo unordered_map?
sobes.tech AI
Odpověď od AI
Pro std::map:
Je třeba definovat operátor porovnání < pro vaši třídu.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Definice operátoru "<"
bool operator<(const MyKey& other) const {
if (id != other.id) {
return id < other.id;
}
return name < other.name;
}
};
int main() {
std::map<MyKey, int> myMap;
MyKey key1{1, "apple"};
MyKey key2{2, "banana"};
myMap[key1] = 10;
myMap[key2] = 20;
return 0;
}
Pro std::unordered_map:
Je třeba definovat hashovací funkci (hasher) pro vaši třídu a pokud je potřeba, i operátor rovnosti ==. Standardní std::hash neumí hashovat uživatelské typy.
Způsoby definice hasheru:
-
Přetížení
std::hashve jmenném prostorustd(nedoporučuje se):#include <unordered_map> #include <string> #include <functional> // Pro std::hash struct MyKey { int id; std::string name; // Definice operátoru "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Specializace std::hash pro MyKey namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Příklad jednoduchého kombinování hashů // Složitější a odolnější hash funkce mohou být vhodnější return hash<int>()(key.id) ^ (hash<std::string>()(key.name) << 1); } }; } int main() { std::unordered_map<MyKey, int> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; } -
Předání hasheru jako šablonového parametru:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Definice operátoru "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Definice struktury hasheru struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // Předání MyKeyHash jako třetího šablonového parametru std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
V obou případech je také potřeba operátor rovnosti == pro std::unordered_map.