在单个集合中合并多个集合元素

cod*_*ack 58 c++ stl set

我想知道是否有任何std库或boost工具可以轻松地将多个集合的内容合并为一个.

在我的情况下,我有一些我想要合并的整数组.

Nic*_*tti 114

你可以这样做:

std::set<int> s1;
std::set<int> s2;
// fill your sets
s1.insert(s2.begin(), s2.end());
Run Code Online (Sandbox Code Playgroud)

  • 我想在合并的上下文中理解insert for multiset和merge之间的区别.插入对每个插入都需要O(logn),所以O(nlogn)总计; 其中n是较小容器的大小.而合并只需要O(n1 + n2).我可以考虑使用insert的唯一原因是它接受任何迭代器以及第二个复杂度在它之前具有三个系数的事实.是否有任何其他强有力的理由支持插入而不是合并. (2认同)
  • 这是次优的解决方案。参见安东尼奥·佩雷斯(AntonioPérez)的答案。 (2认同)
  • 真正.如果没有设置输出,我没有考虑插入.好吧,这样两者都在O(n*log(n))(假设集相等).抱歉咆哮. (2认同)

Ant*_*rez 36

看起来像你要求的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
Run Code Online (Sandbox Code Playgroud)

  • 如果您不需要更改原始结构,此解决方案是最好的. (4认同)

Man*_*ddy 10

使用C++ 17,您可以直接使用merge功能set.

当您希望将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)
Run Code Online (Sandbox Code Playgroud)

  • zh.cppreference.com/w/cpp/container/set/merge。复杂度N * log(size()+ N)),其中N是source.size(),我想最好在答案中增加复杂度,因为这与将所有人都插入其中是相同的? (2认同)

Nel*_*aar 9

看看std :: merge能为你做些什么

cplusplus.com/reference/algorithm/merge