c++ - 指定哈希函数时在 unordered_map<> 中使用默认存储桶计数
问题描述
我正在使用 unordered_map<> 并且很好奇,在将哈希函数指定为第二个参数(下面的每个代码)时,size_type n
必须将存储桶计数指定为构造函数中的第一个参数。我已阅读应使用默认存储桶计数。有谁知道在使用自己的哈希函数时如何使用默认的桶计数参数?
有趣的是,Stroustrup C++ 第 4 版第 918 页构造了一个 unordered_set<> 而不使用桶大小,并且不同意记录的构造函数参数。
explicit unordered_map ( size_type n = /* see below */,
const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type() );
示例用法:
#include <unordered_map>
#include <functional>
#include <iostream>
using namespace std;
struct X {
X(string n) : name{n} {}
string name;
bool operator==(const X& b0) const { return name == b0.name; }
};
namespace std {
template<>
struct hash<X> {
size_t operator()(const X&) const;
};
size_t hash<X>::operator()(const X& a) const
{
cout << a.name << endl;
return hash<string>{}(a.name);
}
}
size_t hashX(const X& a)
{
return hash<string>{}(a.name);
}
int main()
{
// unordered_map<X,int,hash<X>> m(100, hash<X>{});
// unordered_map<X,int,function<size_t(const X&)>> m(100, &hashX);
unordered_map<X,int,size_t(*)(const X&)> m(100, &hashX);
X x{"abc"};
m[x] = 1;
int i = m[x];
cout << i << endl;
}
解决方案
似乎我们可以访问该bucket_count
值。我将在您的环境中运行以下代码并检查它为您提供的值。
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m;
std::cout << m.bucket_count() << std::endl;
return 0;
}
这1
在ideone中输出
推荐阅读
- firebase - 如何根据 Flutter 中的时间戳对 Firestore 流进行排序
- javascript - 如何创建一组模态?
- python - 在 Python 中解析 JSON 结果时出现 KeyError
- python - 使用 imap 连接到 gmail
- xml - 我无法让我的 Powershell 脚本将多个更改保存到我的 xml 文件
- lua - 尝试使用“LoadCharacter”索引 nil
- javascript - 使用 promise 在循环中填充数组
- model - 从子模型调用 json 数据
- javascript - Vue表单提交两次或一次并为空
- mongodb - 如何计算 mongoDB 中嵌入的数组对象元素