C++ 将多个集合元素合并为一个集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7089494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:27:42  来源:igfitidea点击:

Merge multiple sets elements in a single set

c++stlset

提问by codeHyman

I would like to know if there is any std library or boost tool to easily merge the contents of multiple sets into a single one.

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

In my case I have some sets of ints which I would like to merge.

就我而言,我有一些想要合并的整数集。

回答by Nicola Musatti

You can do something like:

您可以执行以下操作:

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

回答by Antonio Pérez

Looks like you are asking for std::set_union.

看起来你是在要求std::set_union.

Example:

例子:

#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

回答by Manohar Reddy Poreddy

With C++17, you can use mergefunction of setdirectly.

在 C++17 中,您可以直接使用 的merge函数set

This is better, when you want the set2 elements extracted & inserted into set1 as part of merging.

当您希望将 set2 元素作为合并的一部分提取并插入到 set1 中时,这会更好。

Like below:

如下图:

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)

回答by Nelstaar

look what std::merge can do for you

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

cplusplus.com/reference/algorithm/merge

cplusplus.com/reference/algorithm/merge