[英]Merging two std::set's and (not yet) std::set::merge()
我只是寫了這段代碼:
// Somewhere earlier, the equivalent of this happens.
std::set<T> a;
std::set<T> b;
FillMeUp(a);
FillMeUp(b);
// Later, in another function that sees a and b, this happens.
std::set<T> c;
std::set_union(a.begin(), a.end(),
b.begin(), b.end(),
std::inserter(c, c.begin()));
a.swap(c);
關鍵是在某些情況下,第二部分代碼希望將a
和b
合並為a
。
(出於動機:我有一個帶有集合的對象數組。我遍歷該數組。如果滿足某個條件,則我正在查看的對象本質上將復制我之前看到的對象,因此我想合並其集合進入之前的集合中。)
C ++ 17中有一個名為std::set::merge
的新函數,但我的g ++ 5.3.1顯然不知道(例如,用-std = c ++ 17調用的g ++ 5.3.1)。
問題是,我真的可以做得比做的更好嗎?
正式地, std::set::merge
在標准草案中定義:
嘗試提取a2中的每個元素,然后使用a的比較對象將其插入到a中。 在具有唯一鍵的容器中,如果a中的某個元素的鍵等於a2中某個元素的鍵,則不會從a2中提取該元素。
具有以下復雜性:
N log(a.size()+ N),其中N的值為a2.size()。
由於這與insert
重載之一的復雜度匹配:
template< class InputIt >
void insert( InputIt first, InputIt last );
聽起來像是光榮的insert
包裝:
a.insert(b.begin(), b.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.