【问题标题】:Pair for unordered strings as key for unordered_map配对无序字符串作为 unordered_map 的键
【发布时间】:2014-06-01 12:34:38
【问题描述】:

可能相关:[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
}

【问题讨论】:

    标签: c++ stl unordered-map


    【解决方案1】:

    对于相同的对象,散列必须始终相等。因此,如果您认为这些实例相等:

    Key s1("John", "Doe");
    Key s2("Doe", "John");
    

    您还必须确保两者的哈希值相同。为此,您可以首先对两个字符串进行排序,然后根据排序后的字符串创建一个哈希。

    【讨论】:

    • 或者你可以在你的哈希函数中进行异或而不需要移位。这可能更容易。
    • 我也怀疑过。非常感谢您帮助我确认我的想法。
    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多