繁体   English   中英

配对无序字符串作为unordered_map的键

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM