有如下代碼:
unordered_set<vector<int>> dict;
上述代碼在編譯時會報錯:
錯誤 C2338 The C++ Standard doesn't provide a hash for this type.
原因如下:
unordered_set和unordered_map本質上都是使用hash方法對元素進行存儲和查找,而C++沒有爲vector定義的默認hash方法,故無法通過編譯。
解決方法1:
自行爲vector定義hash操作,如:
struct VectorHash {
size_t operator()(const std::vector<int>& v) const {
std::hash<int> hasher;
size_t seed = 0;
for (int i : v) {
seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
return seed;
}
};
using MySet = std::unordered_set<std::vector<int>, VectorHash>;
之後就可以這麼使用:
MySet dict;
dict.insert(vector<int>{0,1});
解決方法2:
我不用vector了!
vector<int> v;
string s;
for(auto i:v){
s = s+to_string(i)+"#";
}
unordered_set<string> dict;
dict.insert(s);
我把你個vector變成string再散列行不行?嗯?你再得瑟一個?