Middle+
Čo je potrebné urobiť, aby ste svoju triedu mohli použiť ako kľúč v map alebo unordered_map?
sobes.tech AI
Odpoveď od AI
Za std::map:
Treba definirati operator uspoređivanja < za vašu klasu.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Definiranje operatora "<"
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;
}
Za std::unordered_map:
Treba definirati funkciju hashiranja (hasher) za vašu klasu i, ako je potrebno, operator uspoređivanja ==. Standardni std::hash ne može hashirati korisničke tipove.
Načini definiranja hashera:
-
Preopterećenje
std::hashu prostoru imenastd(nije preporučljivo):#include <unordered_map> #include <string> #include <functional> // Za std::hash struct MyKey { int id; std::string name; // Definira operator "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Specijalizacija std::hash za MyKey namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Jednostavan primjer kombiniranja hashova // Složenije i stabilnije hash funkcije mogu biti poželjnije 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; } -
Prijenos hashera kao šablonskog parametra:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Definira operator "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Definicija strukture za hashiranje struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // Prijenos MyKeyHash kao treći šablonski parametar std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
U oba slučaja za std::unordered_map je također potreban operator za uspoređivanje ==.