C ++无序向量集 [英] C++ unordered_set of vectors

查看:66
本文介绍了C ++无序向量集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在C ++中创建向量的无序集合吗?

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< std :: vector< int>> )将不会实现。例如,根据此答案,我们可以构建:

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< T> 请注意,此可能是的未定义行为,使用 std :: vector< int> ; ,但绝对可以使用用户定义的类型):

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 ++无序向量集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆