[英]Pair for unordered strings as key for unordered_map
可能相關:[ 成對的Unordered-MultiMap, 使用自定義類類型作為鍵的C ++ unordered_map ]
我想使用一對無序字符串作為unordered_map的鍵。
例如,我希望key1與key2相同
key1 = {“ john”,“ doe”}; key2 = {“ doe”,“ john”};
也許我在這里錯過了一些非常愚蠢的東西。
這是我的測試代碼(無法正常運行):
struct Key {
std::string first;
std::string second;
Key(std::string a, std::string b)
{
first = a;
second = b;
}
bool operator==(const Key k) const
{
return ((first == k.first && second == k.second) ||
(first == k.second && second == k.first));
}
};
struct KeyHash {
std::size_t operator()(const Key& k) const
{
return std::hash<std::string>()(k.first) ^
(std::hash<std::string>()(k.second) << 1);
}
};
struct KeyEqual {
bool operator()(const Key& lhs, const Key& rhs) const
{
//return (lhs.first == rhs.first && lhs.second == rhs.second); // not this
return ((lhs.first == rhs.first && lhs.second == rhs.second) ||
(lhs.first == rhs.second && lhs.second == rhs.first));
}
};
void test_unorderedMap()
{
Key s1("John", "Doe");
Key s2("Doe", "John");
Key s3("Mary", "Sue");
Key s4("Sue", "Mary");
// first attempt
std::unordered_map<Key, std::string, KeyHash> m1;
m1[s1] = "a";
m1[s2] = "b";
m1[s3] = "c";
m1[s4] = "d";
std::cout << "m6[s1] : " << m1.find(s1)->second << std::endl; // prints .. a
std::cout << "m6[s2] : " << m1.find(s2)->second << std::endl; // prints .. b
std::cout << "m6[s3] : " << m1.find(s3)->second << std::endl; // prints .. c
std::cout << "m6[s4] : " << m1.find(s4)->second << std::endl; // prints .. d
// second attempt
std::unordered_map<Key, std::string, KeyHash, KeyEqual> m2;
m2[s1] = "a";
m2[s2] = "b";
m2[s3] = "c";
m2[s4] = "d";
std::cout << "m2[s1] : " << m2.find(s1)->second << std::endl; // prints .. a
std::cout << "m2[s2] : " << m2.find(s2)->second << std::endl; // prints .. b
std::cout << "m2[s3] : " << m2.find(s3)->second << std::endl; // prints .. c
std::cout << "m2[s4] : " << m2.find(s4)->second << std::endl; // prints .. d
}
對於相同的對象,哈希值必須始終相等。 因此,如果您認為這些實例相等:
Key s1("John", "Doe");
Key s2("Doe", "John");
您還必須確保兩者的哈希值相同。 為此,例如,您可以首先對兩個字符串進行排序,然后根據排序后的字符串創建哈希。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.