2011-12-10 166 views
2

我來自一個相當功能的編程背景,我不習慣(高效的)C++數據結構。我需要一個數據結構來保存多個元素,如struct element中所述。在集合中,字段ID應該是唯一的。集合論數據結構

我想執行像在比較組{x1,x2,x3}{x4,x5}我要確定交集{x5}(或{x2}其在這種情況下相等)和。減去集從其它時集合論即例如非常快的設定比較設置像例如{x1,x2,x3} \ {x5} = {x1,x3}

在C++的宇宙中是否存在「設置理論」數據結構?

struct element { 
int id; 
float value; 
}; 

struct element x1 = {1, 1.0}; 
struct element x2 = {2, 2.0}; 
struct element x3 = {3, 3.0}; 

struct element x4 = {3, 3.1}; 
struct element x5 = {2, 2.0}; 
+0

std :: set是你在找什麼。 http://www.cplusplus.com/reference/stl/set/請注意,您需要一個比較運算符。 – Lalaland

+0

''中的'std :: set'。 http://stdcxx.apache.org/doc/stdlibug/8-2.html – birryree

+0

而且,在std :: set中有些東西在中,比如std :: set_union http://www.cplusplus.com/reference/算法/ – Lalaland

回答

5

std::set,它實現動態集合(動態裝置元件可以被插入或刪除)。爲了使它適用於您的element結構,您需要一個自定義比較函數,該函數僅適用於id。或者,您可以使用std::map<int, float>,這可能更適合您的問題。

要找到兩組的交集,請使用std::set_intersection算法。這需要排序的範圍,其中包括迭代器的範圍分爲std::setstd::map。有關區別,請使用std::set_difference

1

只是要提到這一點,因爲是一個真正偉大的數據結構,集交易,但它不套房,您的所有需求時,

但你仍然可以把它記住,如果你有這樣的要求,

1)查詢,其設置元素屬於

2)聯盟不同組

無論在子對數時間,即幾乎不變的。其所謂的不相交集數據結構 http://en.wikipedia.org/wiki/Disjoint-set_data_structure

1
struct element { 
    int id; 
    float value; 

    element(int id_=0, float value_=0.0) : id(id_), value(value_) {} 

    bool& operator==(const element& e) const 
    { 
     return id==e.id && value==e.value; 
    } 
}; 

element e1(1,1.0); 

std::set<element> set_; 
set_.insert(e1); 

結帳STD算法可以執行的操作。 http://www.cplusplus.com/reference/algorithm/