C++ unordered_set 向量

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

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

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

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

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就可以了,但是在尝试使用无序版本时我收到一个编译错误

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

当然可以.不过,您必须提出一个哈希值,因为默认值 (std::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>;

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

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

本文链接:https://www.f2er.com/3186440.html

大家都在问