来自 http://en.cppreference.com/w/cpp/container/unordered_map/unordered_map , unordered_map
可以使用 lambda 函数作为哈希函数。也在下面回答:How to use lambda function as hash function in unordered_map?
我的问题是关于散列 struct
其中包括 container
,说一个 vector
.自 cpprefence
有如下代码示例
#include <algorithm>
#include <cassert>
#include <string>
#include <unordered_set>
#include <vector>
#include <unordered_map>
using std::hash;
using std::string;
using std::unordered_set;
using std::vector;
int main(int argc, char* argv[]) {
struct Goo {int val; };
auto hash = [](const Goo &g){ return std::hash<int>{}(g.val); };
auto comp = [](const Goo &l, const Goo &r){ return l.val == r.val; };
std::unordered_map<Goo, double, decltype(hash), decltype(comp)> m8(10, hash, comp);
return 0;
}
我修改了它,让它尝试使用 vector<int>
在Goo
.
#include <algorithm>
#include <cassert>
#include <string>
#include <unordered_set>
#include <vector>
#include <unordered_map>
using std::hash;
using std::string;
using std::unordered_set;
using std::vector;
int main() {
using vint = std::vector<int>;
struct Goo { vint v; };
auto hash = [](const Goo &g){
std::size_t hash_value = 0;
for (const int& i : g.v) {
hash_value ^= std::hash<int>{}(i);
}
return hash_value;
};
auto comp = [](const Goo &l, const Goo &r){
return unordered_set<int>(l.v.begin(), l.v.end()) ==
unordered_set<int>(r.v.begin(), r.v.end());
};
vint here;
std::unordered_map<Goo, double, decltype(hash), decltype(comp)>
m8(here,0, hash, comp);
return 0;
}
此代码无法编译。编译器提示不是 no matching function for call to ‘std::unordered_map<main(int, char**)::Goo
.参数的数量似乎不是问题,但一定是某些地方工作不正常。非常感谢您的指导。
顺便说一下,我正在使用 g++ -std=c++17。
最佳答案
我认为你没有理解这个例子。这一行:
std::unordered_map<Goo, double, decltype(hash), decltype(comp)> m8(10, hash, comp);
负责创建至少有 10 个桶的 unordered_map,并提供 hash 和 comp 函数。它不会创建任何包含 10 个元素的 unordered_map。因此,您的代码应如下所示:
using vint = std::vector<int>;
struct Goo { vint v; };
auto hash = [](const Goo &g){
std::size_t hash_value = 0;
for (const int& i : g.v) {
hash_value ^= std::hash<int>{}(i);
}
return hash_value;
};
auto comp = [](const Goo &l, const Goo &r){
return std::unordered_set<int>(l.v.begin(), l.v.end()) ==
std::unordered_set<int>(r.v.begin(), r.v.end());
};
std::unordered_map<Goo, double, decltype(hash), decltype(comp)>
m8(10, hash, comp);
unordered_map 根本没有任何可以处理这个的构造函数:
std::unordered_map<Goo, double, decltype(hash), decltype(comp)>
m8(here, 0, hash, comp);
关于c++ - 在 unordered_map<vector<T>> 中使用 lambda 函数进行散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039527/