理解' std::unordered_set '的用法

Understand the usage of `std::unordered_set`

本文关键字:用法 set unordered std 理解      更新时间:2023-10-16
#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;
}

问题1> unordered_set是否使用MN::operator==来检查新项目是否重复?

问题2> unordered_set是否使用'MNHash'来计算新项目的哈希键?

问题3>如果Q1和Q2的答案都是YES,那么我们是否会在about代码中看到哈希冲突,因为MN(2,3)和MN(3,2)具有相同的哈希码?

谢谢

  1. 多或少。std::unordered_set的默认比较器将使用std::equal_to,除非专门指定,否则它将执行return lhs == rhs

    您可以通过专门化std::equal_to或向std::unordered_set添加第三个模板参数来改变这一点。

  2. 它将使用第二个模板参数来计算哈希值。在本例中,您已经通过了MNHash,因此它将使用它来完成工作。

  3. 由于MN(2,3)MN(3,2)的哈希值相同,它们将被放置在同一个bucket中