簡體   English   中英

C++ unordered_set 向量

[英]C++ unordered_set of vectors

我可以在 C++ 中創建一個 unordered_set 向量嗎? 像這樣的

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

因為我知道 std lib 的“set”class 是可能的,但它似乎不適用於無序版本,謝謝

更新:這正是我要使用的代碼

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

你當然可以。 不過,您必須提出一個哈希值,因為默認值( 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;
    }
};

進而:

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

如果您願意,您也可以為這種類型添加一個專門化到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>>;

作為自定義編寫的散列器的替代方案,Boost 為許多標准庫類型提供了散列器。 這應該適用於您的情況:

#include <boost/container_hash/hash.hpp>

std::unordered_set<
  std::vector<int>,
  boost::hash<std::vector<int>>
> s1;

參考: https://www.boost.org/doc/libs/1_78_0/doc/html/hash/reference.html

在舊的 Boost 版本中,header 文件是boost/functional/hash.hpp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM