Middle+
Ką reikia padaryti, kad savo klasę naudotumėte kaip raktą map arba unordered_map?
sobes.tech AI
Atsakymas iš AI
„std::map“:
Reikia apibrėžti palyginimo operatorių < jūsų klasei.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Apibrėžiame „<“ operatorių
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;
}
„std::unordered_map“:
Reikia apibrėžti maišos funkciją (hasher) jūsų klasei ir, jei reikia, lygumo operatorių ==. Standartinis std::hash negali maišyti naudotojo tipų:
Maišos funkcijos apibrėžimo būdai:
-
Perrašyti
std::hashstdvardų erdvėje (nerekomenduojama):#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Apibrėžiame `==` operatorių bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Specializacija `std::hash` MyKey tipui namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Paprastas hashų sujungimas // Sudėtingesnės ir stabilesnės hash funkcijos gali būti pageidautinos 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; } -
Hesheri perduoti kaip šablono parametrą:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Apibrėžiame `==` operatorių bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Hesherio struktūros apibrėžimas struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // Perdavimo `MyKeyHash` kaip trečio šablono parametro std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
Abiem atvejais std::unordered_map taip pat reikalingas lygumo operatorius ==.