Middle+
O'z sinfingizni map yoki unordered_map ichida kalit sifatida ishlatish uchun nima qilish kerak?
sobes.tech AI
AIdan javob
std::map uchun:
Sizning sinfingiz uchun < taqqoslash operatorini aniqlash kerak.
#include <map>
#include <string>
struct MyKey {
int id;
std::string name;
// "<" operatorini aniqlaymiz
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 uchun:
Sizning sinfingiz uchun hash funksiyasini (hasher) aniqlash va, agar kerak bo'lsa, == tenglik operatorini ham belgilash kerak. Standart std::hash tipi uchun maxsus hash funksiyasi mavjud emas.
Hash funksiyasini aniqlash usullari:
-
stdnom space ichidastd::hashni ortiqcha yuklash (maslahat berilmaydi):#include <unordered_map> #include <string> #include <functional> // std::hash uchun struct MyKey { int id; std::string name; // "==" operatorini aniqlaymiz bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // MyKey uchun std::hash'ni maxsuslashtirish namespace std { template <> struct hash<MyKey> { size_t operator()(const MyKey& key) const { // Oddiy hashlarni birlashtirish misoli // Murakkab va mustahkam hash funksiyalari afzalroq bo'lishi mumkin 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; } -
Hash funksiyasini shablon parametr sifatida o'tkazish:
#include <unordered_map> #include <string> #include <functional> struct MyKey { int id; std::string name; // "==" operatorini aniqlaymiz bool operator==(const MyKey& other) const { return id == other.id && name == other.name; } }; // Hash strukturasini aniqlash struct MyKeyHash { size_t operator()(const MyKey& key) const { return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1); } }; int main() { // MyKeyHashni shablon parametr sifatida o'tkazamiz std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap; MyKey key1{1, "apple"}; MyKey key2{2, "banana"}; myUnorderedMap[key1] = 10; myUnorderedMap[key2] = 20; return 0; }
Har ikkala holatda ham, == tenglik operatori ham std::unordered_map uchun zarur.