合并两个 std::set 和(尚未) std::set::merge()
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显然不知道它(说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());
相关文章:
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将 std::set 与基于键的比较器一起使用
- 修改"std::set"中用户定义类型的值
- 如何在构造函数参数中初始化"std::set"?
- 如何使用 lower_bound/upper_bound 从 std::set 获取索引号?
- 如何在 C++ 中转发声明 std::set?
- 重构使用动态强制转换的 std::set 的比较运算符
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- std::set 是否将对象连续存储在内存中?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 我从 std::set 得到const_iterator而不是迭代器
- 为什么 std:set(带有单个冒号)可以编译?
- 遍历 std::set 中包含的所有三重不同值?
- 插入 std::set 作为 std::map 的键
- 如何在 c++ 中使用默认值将 std::set 转换为 std::map
- 错误:'class std::unique_ptr<std::set<long unsigned int> >'没有名为 'size' 的成员
- 如何从 std::set 绘制 n 个元素的样本
- 为什么 std::set 容器使用的内存比其数据大小多得多?