将多个集合元素合并为一个集合
Merge multiple sets elements in a single set
我想知道是否有任何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中,可以直接使用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)
看看std::merge能为您做些什么
cplusplus.com/reference/algorithm/merge
相关文章:
- 实现一个在集合上迭代的模板函数
- 如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
- 仅从无序集合中删除一个项目
- 如何从一个无序集合中获取一个元素
- 大三实现在一个集合类
- (也许是NP-Hard)求一个集合的子集总数,使得每个子集在与其所有元素相乘时的值都大于X
- 如何在C 中输出集合的最后一个元素
- 一个类用于集合和字典 (map)
- 创建一个抽象类类型的集合,shared_ptr的抽象类向量
- 模板模板集合接受另一个模板参数
- 将“Eigen::VectorXd”的集合合并为一个大的“Eigen::VectorXd”
- Qt:为模板(映射、列表、集合等)构建一个可变迭代器
- 维护多集中数字的排序列表和另一个集合中的累积总和
- C 迭代器到集合的最后一个元素
- 如果对象尚未在集合中,则创建一个对象
- std::set的替代品(可以将元素从一个集合移动到另一个集合)
- 检查当前元素是否是集合的最后一个元素
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 只有Arduino的第一个对象在包含在另一个对象的集合/数组中时会丢失其数据属性值
- 如果您在c++中更新一个集合的成员,该集合会自动更改顺序吗