Middle+
Τι πρέπει να κάνετε για να χρησιμοποιήσετε την κλάση σας ως κλειδί σε ένα map ή unordered_map;
sobes.tech AI
Απάντηση από AI
Για std::map:
Είναι απαραίτητο να ορίσετε τον τελεστή σύγκρισης < για την κλάση σας.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// Ορίζουμε τον τελεστή "<"
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:
Είναι απαραίτητο να ορίσετε μια συνάρτηση κατακερματισμού (hasher) για την κλάση σας και, αν χρειάζεται, τον τελεστή σύγκρισης ισότητας ==. Ο προεπιλεγμένος std::hash δεν μπορεί να κατακερματίσει προσαρμοσμένους τύπους.
Τρόποι ορισμού του hasher:
-
Υπερφόρτωση του
std::hashστον χώρο ονομάτωνstd(δεν συνιστάται):#include <unordered_map> #include <string> #include <functional> // Για std::hash struct MyKey { int id; std::string name; // Ορίζουμε τον τελεστή "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Εξειδίκευση του std::hash για το MyKey namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Παράδειγμα απλής συνδυασμένης κατακερματισμού // Πιο πολύπλοκες και ανθεκτικές συναρτήσεις κατακερματισμού μπορεί να προτιμώνται 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; } -
Μεταβίβαση του hasher ως πρότυπο παράμετρο:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // Ορίζουμε τον τελεστή "==" bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Ορισμός δομής 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() { // Μεταβίβαση του MyKeyHash ως τρίτη παράμετρο πρότυπου std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
Σε και τις δύο περιπτώσεις, απαιτείται επίσης ο τελεστής σύγκρισης ==.