可能相关:[Unordered-MultiMap of Pairs,C++ unordered_map using a custom class type as the key]
我想使用一对无顺序字符串作为我的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
}
答案 0 :(得分:1)
对于相同的对象,哈希必须始终相等。因此,如果您认为这些实例相等:
Key s1("John", "Doe");
Key s2("Doe", "John");
您还必须确保两者的哈希值相同。为此,您可以首先对两个字符串进行排序,并根据排序的字符串创建一个哈希值。