【发布时间】:2011-10-28 16:53:47
【问题描述】:
我想知道是否有任何 std 库或 boost 工具可以轻松地将多个集合的内容合并为一个。
就我而言,我有一些想要合并的整数集。
【问题讨论】:
我想知道是否有任何 std 库或 boost 工具可以轻松地将多个集合的内容合并为一个。
就我而言,我有一些想要合并的整数集。
【问题讨论】:
看来您要的是std::set_union。
例子:
#include <set>
#include <algorithm>
std::set<int> s1;
std::set<int> s2;
std::set<int> s3;
// Fill s1 and s2
std::set_union(std::begin(s1), std::end(s1),
std::begin(s2), std::end(s2),
std::inserter(s3, std::begin(s3)));
// s3 now contains the union of s1 and s2
【讨论】:
使用C++17,可以直接使用set的merge函数。
当您希望将 set2 元素提取并插入到 set1 作为合并的一部分时,这会更好。
如下:
set<int> set1{ 1, 2, 3 };
set<int> set2{ 1, 4, 5 };
// set1 has 1 2 3 set2 has 1 4 5
set1.merge(set2);
// set1 now has 1 2 3 4 5 set2 now has 1 (duplicates are left in the source, set2)
【讨论】:
insert 所以你可以合并但复制?就像构建一个临时的并合并它一样简单:insert(set input) { merge(set(input)); }
看看 std::merge 能为你做什么
【讨论】:
你可以这样做:
std::set<int> s1;
std::set<int> s2;
// fill your sets
s1.insert(s2.begin(), s2.end());
【讨论】:
std::set_union() 的性能时,您应该考虑重复调用std::set::insert() 的成本。