简体   繁体   English

了解`std :: unordered_set`的用法

[英]Understand the usage of `std::unordered_set`

#include <iostream>
#include <cmath>
#include <unordered_set>
using namespace std;

struct MN
{
    MN(const int& _m, const int& _n)
        : m(_m), n(_n) {
            value = pow (m, n);
        }

    bool operator==(const MN& rhs) const {
        return m == rhs.m && n == rhs.n;
    }

    int value;      
    int m;
    int n;
};

struct MNHash
{
    size_t operator()(const MN& rhs) const {
        return hash<int>()(rhs.m) ^ hash<int>()(rhs.n);
    }
};

int main() {
    unordered_set<MN, MNHash> st;
    st.emplace(2, 3);
    st.emplace(3, 2);

    cout << st.size() << endl; // 2
    return 0;
}

Question 1> Is it true that the unordered_set uses MN::operator== to check whether the new item is duplicate or not? 问题1> unordered_set使用MN::operator==检查新项目是否重复?

Question 2> Is it true that the unordered_set uses 'MNHash' to compute the hash key of the new item? 问题2> unordered_set使用'MNHash'计算新项目的哈希键是否正确?

Question 3> If the answers to both Q1 and Q2 are YES, then is it true that we will see a hash conflict in about code because both MN(2, 3) and MN(3, 2) have the same hash code? 问题3>如果对Q1和Q2的回答都是“是”,那么因为MN(2,3)和MN(3,2)具有相同的哈希码,我们是否会在about代码中看到哈希冲突?

Thank you 谢谢

  1. More or less. 或多或少。 The default comparator for std::unordered_set will use std::equal_to , which, unless specialized, will do return lhs == rhs . std::unordered_set的默认比较器将使用std::equal_to ,除非专门指定,否则将return lhs == rhs

    You can change this by either specializing std::equal_to , or by adding a third template argument to the std::unordered_set . 您可以通过专用于std::equal_to或通过向std::unordered_set添加第三个模板参数来更改此设置。

  2. It will use the second template argument to compute the hash. 它将使用第二个模板参数来计算哈希值。 In this case, you've passed MNHash , so it will use that to do the work. 在这种情况下,您已经传递了MNHash ,因此它将使用它来完成工作。

  3. Since the hash value of MN(2,3) and MN(3,2) are the same, they will be placed in the same bucket. 由于MN(2,3)MN(3,2)的哈希值相同,因此它们将放置在同一存储桶中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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