我知道集合是有序的,因此在不重载<
运算符的情况下添加对象不允许说哪个对象较小以使容器保持排序。但是,我不明白为什么unordered_set
无法做到这一点。
如果我尝试这样的事情:
#include <iostream>
#include <string
#include <unordered_set>
struct someType{
string name;
int code;
};
int main(){
std::unordered_set <someType> myset;
myset.insert({"aaa",123});
myset.insert({"bbb",321});
myset.insert({"ccc",213});
return 0;
}
我收到一些错误,例如:为什么会这样,我该如何解决?
最佳答案
要在unordered_set或unordered_map中使用类型,您需要为类型使用哈希函数。对于int
或std::string
等常见类型,标准库提供了哈希函数。对于您的类型,您可以重载标准std::hash
,如下所示:
namespace std {
template <> struct hash<someType> {
size_t operator()(const someType & x) const {
std::hash<std::string> h;
return h(x.name);
// or simply return x.code
// or do something more interesting,
// like xor'ing hashes from both members of struct
}
};
}
另一种方法是为您自己的类型提供重载的
operator()
并将其作为哈希模板参数放入unordered_set中,如下所示:struct someTypeHasher {
size_t operator()(const someType& x) const {
return x.code;
}
};
std::unordered_set<someType, someTypeHasher> myset;
好的阅读有关基于散列的容器的理论是here
同样,不要忘记,您需要为
operator==
重载someType
,否则,它也将无法正常工作。关于c++ - 为什么不能将对象存储在unordered_set中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40751531/