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

Merge multiple sets elements in a single set

本文关键字:集合 一个 合并 元素      更新时间:2023-10-16

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

在我的例子中,我有一些整型数的集合我想要合并

你可以这样做:

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

看来你要的是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中,可以直接使用setmerge函数

这是更好的,当你想提取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)

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

cplusplus.com/reference/algorithm/merge