理解' 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;
}
问题1> unordered_set
是否使用MN::operator==
来检查新项目是否重复?
问题2> unordered_set
是否使用'MNHash'来计算新项目的哈希键?
问题3>如果Q1和Q2的答案都是YES,那么我们是否会在about代码中看到哈希冲突,因为MN(2,3)和MN(3,2)具有相同的哈希码?
谢谢
-
多或少。
std::unordered_set
的默认比较器将使用std::equal_to
,除非专门指定,否则它将执行return lhs == rhs
。您可以通过专门化
std::equal_to
或向std::unordered_set
添加第三个模板参数来改变这一点。 -
它将使用第二个模板参数来计算哈希值。在本例中,您已经通过了
MNHash
,因此它将使用它来完成工作。 -
由于
MN(2,3)
和MN(3,2)
的哈希值相同,它们将被放置在同一个bucket中
相关文章:
- 为什么我无法更改"set<set>"循环中的值<int>
- 这个指针在c++中的用法
- 对于set上的循环-获取next元素迭代器
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 当C++中需要自动删除时,这是静态的正确用法吗?
- 将 std::set 与基于键的比较器一起使用
- 如何使用set实现无序数据结构?
- libstdc++ 文件系统中未初始化的用法?
- 使用运算符调用 void 函数时出错<set>
- 复制和交换习惯用法与移动操作之间的交互
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 命名参数习惯用法和(抽象)基类
- 修改"std::set"中用户定义类型的值
- 省略号在C++中的所有用法
- () 在 C++ 11 中的特殊而奇怪的用法?
- 构造函数的用法
- 模板类中自动的类用法不完整
- 生成提升::hana::set 的常量表达式问题
- 如何在构造函数参数中初始化"std::set"?