C++ unordered

编程入门 行业动态 更新时间:2024-10-09 10:20:18
本文介绍了C++ unordered_set 向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以在 C++ 中创建一个 unordered_set 向量吗?像这样

Can I create a unordered_set of vectors in C++? something like this

std::unordered_set<std::vector<int>> s1;

因为我知道使用 std lib 的set"类是可能的,但似乎它不适用于无序版本谢谢

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

更新:这正是我要使用的代码

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 };

如果我使用set就可以了,但是在尝试使用无序版本时我收到一个编译错误

and it's all right if I use set, but I receive a compilation error when try to use the unordered version

main.cpp:46:11: error: non-aggregate type 'Route' (aka 'vector<CustomerId>') cannot be initialized with an initializer list Route r3 = { 9, 7 };

推荐答案

当然可以.不过,您必须提出一个哈希值,因为默认值 (std::hash) 将不会实现.例如,基于这个答案,我们可以构建:

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. 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; } };

然后:

using MySet = std::unordered_set<std::vector<int>, VectorHash>;

如果您愿意,您也可以为这种类型的 std::hash 添加专门化(注意这可以em> 是 std::vector 的未定义行为,但对于用户定义的类型绝对没问题):

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):

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>>;

更多推荐

C++ unordered

本文发布于:2023-11-29 01:50:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644817.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:unordered

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!