Middle+
Ce trebuie făcut pentru a folosi clasa ta ca cheie într-un map sau unordered_map?
sobes.tech AI
Răspuns de la AI
Pentru std::map:
Este necesar să definiți operatorul de comparație < pentru clasa dvs.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Definiți operatorul "<"
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;
}
Pentru std::unordered_map:
Este necesar să definiți o funcție de hash (hasher) pentru clasa dvs. și, dacă este necesar, operatorul de comparație pentru egalitate ==. Hash-ul standard std::hash nu poate face hash de tipuri personalizate.
Modalități de definire a hasher-ului:
-
Suprascrierea
std::hashîn spațiul de numestd(nu recomandat):#include <unordered_map> #include <string> #include <functional> // Pentru std::hash struct MyKey { int id; std::string name; // Definiți operatorul "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Specializare a std::hash pentru MyKey namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Exemplu de combinare simplă a hash-urilor // Funcții de hash mai complexe și robuste pot fi preferate 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; } -
Transmiterea hasher-ului ca parametru de șablon:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Definiți operatorul "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Definirea structurii hasher struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // Transmiterea lui MyKeyHash ca al treilea parametru de șablon std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
În ambele cazuri, este necesar și operatorul de comparație pentru egalitate ==.