C++ unordered_set向量

Cat*_*one 22 c++ vector c++11

我可以在C++中创建一个无序的向量集吗?这样的事情

std::unordered_set<std::vector<int>> s1;
Run Code Online (Sandbox Code Playgroud)

因为我知道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 };
Run Code Online (Sandbox Code Playgroud)

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

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

Bar*_*rry 34

你当然可以.但是你必须提出一个哈希值,因为默认的one(std::hash<std::vector<int>>)不会被实现.例如,基于这个答案,我们可以构建:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后:

using MySet = std::unordered_set<std::vector<int>, VectorHash>;
Run Code Online (Sandbox Code Playgroud)

如果您愿意,也可以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>>;
Run Code Online (Sandbox Code Playgroud)

  • @Divyansh 没有 `std::hash&lt;std::vector&lt;int&gt;&gt;` - 标准库不提供它。 (3认同)
  • 下半场可能是UB。就库而言,我不认为 `std::vector&lt;int&gt;` 算作用户定义的类型。 (2认同)
  • @NanoNi `std::set` 不是哈希表,它是二叉树。它使用`&lt;` (2认同)