From http://en.cppreference.com/w/cpp/container/unordered_map/unordered_map, unordered_map
can use lambda functions for hashing function. It is also answered in the following: How to use lambda function as hash function in unordered_map?
My question is about hashing a struct
which includes a container
, say a vector
. Since cpprefence
has the following code example of
#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;
}
I have modified it so that it tries to use vector<int>
in the 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;
}
This code doesn't compile. The compiler complains about not no matching function for call to ‘std::unordered_map<main(int, char**)::Goo
. The number of arguments seems to be not the issue, but something must be working not correctly. I would greatly appreciate your guidance.
I am using g++ -std=c++17 by the way.