我正在使用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;
}发布于 2020-07-31 03:22:18
看起来我们可以访问bucket_count值了。我只需在您的环境中运行以下代码,并检查它为您提供了什么值。
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m;
std::cout << m.bucket_count() << std::endl;
return 0;
}这将在ideone中输出1
https://stackoverflow.com/questions/63179462
复制相似问题