Middle+
Mit kell tenni ahhoz, hogy a saját osztályodat kulcsként használd egy map vagy unordered_map esetén?
sobes.tech MI
Válasz az MI-től
A std::map-hez:
Meg kell határozni az összehasonlító operátort < az osztályodhoz.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Az "<" operátor meghatározása
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;
}
A std::unordered_map-hoz:
Meg kell határozni a hash függvényt (hashert) az osztályodhoz, és ha szükséges, az egyenlőség operátort ==. A standard std::hash nem képes felhasználói típusokat hash-elni.
Hasonló módszerek a hashelő meghatározására:
-
A
std::hashtúlterhelése astdnévtérben (nem ajánlott):#include <unordered_map> #include <string> #include <functional> // A std::hash-hoz struct MyKey { int id; std::string name; // Az "==" operátor meghatározása bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // A std::hash specializálása MyKey-re namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Egyszerű kombinációs példa // bonyolultabb és stabilabb hash függvények előnyösebbek lehetnek 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; } -
Hashelő átadása sablonparaméterként:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Az "==" operátor meghatározása bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // A hash szerkezet meghatározása struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // A MyKeyHash átadása a harmadik sablonparaméterként std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
Mindkét esetben az == egyenlőség operátor is szükséges a std::unordered_map-hez.