[英]C++ unordered_set of vectors
Can I create a unordered_set of vectors in C++?我可以在 C++ 中创建一个 unordered_set 向量吗? something like this
像这样的
std::unordered_set<std::vector<int>> s1;
because I know that is possible with the "set" class of the std lib but seems that it doesn't work for the unordered version thanks因为我知道 std lib 的“set”class 是可能的,但它似乎不适用于无序版本,谢谢
Update: this is the exactly code that I'm trying to use更新:这正是我要使用的代码
typedef int CustomerId;
typedef std::vector<CustomerId> Route;
typedef std::unordered_set<Route> Plan;
// ... in the main
Route r1 = { 4, 5, 2, 10 };
Route r2 = { 1, 3, 8 , 6 };
Route r3 = { 9, 7 };
Plan p = { r1, r2 };
and it's all right if I use set, but I receive a compilation error when try to use the unordered version如果我使用 set 就没问题,但是当我尝试使用无序版本时收到编译错误
main.cpp:46:11: error: non-aggregate type 'Route' (aka 'vector<CustomerId>') cannot be initialized with an initializer list
Route r3 = { 9, 7 };
Sure you can.你当然可以。 You'll have to come up with a hash though, since the default one (
std::hash<std::vector<int>>
) will not be implemented.不过,您必须提出一个哈希值,因为默认值(
std::hash<std::vector<int>>
)将不会实现。 For example, based on this answer , we can build:例如,基于这个答案,我们可以构建:
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;
}
};
And then:进而:
using MySet = std::unordered_set<std::vector<int>, VectorHash>;
You could also, if you so choose, instead add a specialization to std::hash<T>
for this type ( note this could be undefined behavior with std::vector<int>
, but is definitely okay with a user-defined type):如果您愿意,您也可以为这种类型添加一个专门化到
std::hash<T>
(注意这可能是std::vector<int>
未定义行为,但对于用户定义的类型绝对没问题):
namespace std {
template <>
struct hash<std::vector<int>> {
size_t operator()(const vector<int>& v) const {
// same thing
}
};
}
using MySet = std::unordered_set<std::vector<int>>;
As an alternative to a custom-written hasher, Boost provides a hasher for many standard library types.作为自定义编写的散列器的替代方案,Boost 为许多标准库类型提供了散列器。 This should work in your case:
这应该适用于您的情况:
#include <boost/container_hash/hash.hpp>
std::unordered_set<
std::vector<int>,
boost::hash<std::vector<int>>
> s1;
Reference: https://www.boost.org/doc/libs/1_78_0/doc/html/hash/reference.html参考: https://www.boost.org/doc/libs/1_78_0/doc/html/hash/reference.html
In older Boost versions, the header file was boost/functional/hash.hpp
.在旧的 Boost 版本中,header 文件是
boost/functional/hash.hpp
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.