2015-04-24 12 views
12

C++ ile bir unordered_set of vectors oluşturabilir miyim? şudur: Ben sayesindeC++ vektörlerin unordered_set'i

Güncelleme std lib "set" sınıfı ile mümkün olduğunu biliyoruz ama sırasız sürümü için çalışmıyor gibi görünüyor, çünkü bu

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

gibi bir şey Ben

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

kullanmaya çalışıyorum ve her şey yolunda belirlediğim kullanın eğer, ama deneyin sırasız sürümünü kullanmak için ne zaman bir derleme hatası alırsınız tam kod

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

Şunu mu demek istediniz: ['std :: unordered_set >'] (http://en.cppreference.com/w/cpp/container/unordered_set) aslında? –

+0

Üzgünüm, yanlış sınıf adını basamıyorum, tam olarak unordered_set demek –

+0

* Nasıl * çalışmıyor? Senin sorunun ne? –

cevap

21

Elbette yapabilirsin. Varsayılan bir (std::hash<std::vector<int>>) uygulanmayacağından, bir karma ile gelmeniz gerekecek. Örneğin, this answer dayanarak, inşa edebilirsiniz: sonra

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

Ve: Bunu seçerseniz

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

Ayrıca, onun yerine bu tip (not için std::hash<T> için bir uzmanlık ekleyebilir Bu std::vector<int> ile tanımsız davranış olabilir, ama) bir kullanıcı tanımlı türü ile kesinlikle tamamdır olabilir:

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

İkinci yarısı muhtemelen UB'dir. Kütüphane söz konusu olduğunda, 'std :: vector 'kullanıcı tanımlı bir tür olarak sayılmıyor. –

+0

@ T.C. Hm. Doğru tespit. Bir not ekledim. – Barry

İlgili konular