【发布时间】:2020-06-23 00:09:01
【问题描述】:
基本上我的问题是,为什么不能编译?
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int main() {
vector<int> v{1,2,3};
auto hash_function=[](const vector<int>& v){
size_t hash;
for (int i = 0; i < v.size(); ++i) {
hash+=v[i]+31*hash;
}
return hash;
};
unordered_set<vector<int>, decltype(hash_function)> s(hash_function);
std::cout<<s.bucket_count();
std::cout<<"here";
}
但如果我将 unordered_set 行更改为此
unordered_set<vector<int>, decltype(hash_function)> s(10,hash_function);
会的。为什么需要初始桶数?使用 lambda 强制我添加初始存储桶计数似乎很奇怪,但使用仿函数则不会。请参阅此处的示例:C++ unordered_set of vectors 以证明仿函数版本不需要初始桶数。
【问题讨论】:
-
我有点困惑。你想使用cplusplus.com/reference/unordered_set/unordered_set/… 的哪个构造函数?
-
换句话说,如果标准选择支持参数的所有组合(默认/迭代器对/初始化器列表 * 可选计数/哈希/相等/分配),那将是 48 个构造函数(默认更少参数),并可能导致重载决议中不同函数对象之间的歧义。所以标准选择了限制构造函数的形式。
-
@L.F.这个评论很有意义。我一直想知道为什么这么多构造函数“失踪”,但看了你是对的,它会导致构造函数的数量迅速增加。
标签: c++ unordered-set