合并两个 std::set 和(尚未) std::set::merge()

Merging two std::set's and (not yet) std::set::merge()

本文关键字:std set 尚未 merge 两个 合并      更新时间:2023-10-16

我刚刚写了这个代码:

// 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);

重点是,在某些情况下,代码的第二位希望将ab合并为a

(出于动机:我有一个带有集合的对象数组。我对该数组进行迭代。如果满足某个条件,我正在查看的对象基本上与我之前看到的对象重复,所以我想将其集合合并到之前的集合中。)

C++17中有一个新函数叫做std::set::merge,但我的g++5.3.1显然不知道它(说g++5.3.1用-std=C++17调用)。

真正的问题是,我能做得比我所做的更好吗?

官方在标准草案中定义了std::set::merge

尝试提取a2中的每个元素,并使用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());