簡體   English   中英

std :: multiset是否保證插入順序?

[英]Does std::multiset guarantee insertion order?

我有一個std::multiset ,它存儲了class A元素。 我為這個類提供了我自己的operator<的實現。 我的問題是,如果我在這個multiset中插入兩個等效對象,他們的順序是否有保證? 例如,首先我將對象a1插入到集合中,然后將等效對象a2插入到此集合中。 當我遍歷集合時,我可以期望a1a2之前到來嗎? 如果不是,有沒有辦法用multiset實現這個目的?

在C ++ 03中,您不能保證inserterase保留相對順序 但是,這在C ++ 0x中已更改:

n3092,§23.2.4/ 4:關聯容器支持唯一鍵,如果每個鍵最多可包含一個元素。 否則,它支持等效鍵。 set和map類支持唯一鍵; multiset和multimap類支持等效鍵。 對於multiset和multimap,插入和擦除保留了等效元素的相對順序。 強調我的。

缺陷報告中對此進行了討論。 這個頁面是關於這個問題的評論集合,它寫得很好並且非常充實。 (我非常推薦通過之前的“概述”鏈接閱讀此內容。)

從該評論頁面中,您將找到當前實現的比較,因此您可以檢查您打算使用的實現是否遵循您的期望。

我想不出一種強制你想要的排序的方法。 :/

考慮到a1a2在你的例子中比較相等,而實際存儲在std::multiset中的是a1a2副本,我真的不知道你怎么知道哪個是哪個。

如果你能說出不同之處,那么class A設計可能並不是很好。 所以std::multiset並不能保證這樣的事情。

std :: multimap不保證這一點。 如果你可以表達你的operator<通過函數使用整數,例如int A::orderingInt() ,你可以使用a

std::multiset<MyCustom> myset;

class MyCustom : public std::vector<A> {}

超載

bool operator<(const MyCustom& a, const MyCustom& b) {
   // theoretically empty MyCustom should not occure
   return a[0].orderingInt() < b[0].orderingInt();
}

當然,添加和迭代現在會有所不同:

A a;
myset[a.orderingInt()].push_back(a);

// groups with "small" elements first
for(std::multiset<MyCustom>::iterator it=myset.begin(); it!=myset.end(); it++) {
    // those elements are "equal"
    for(std::vector<A>::iterator jt=it->begin(); jt->end(); jt++) { 
         // use A& a = *jt;
    }
}

暫無
暫無

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

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