std::set的联合操作
Union Operation For std::set
标准库中没有这样的函数吗?
set<T> set::union(set<T> other)
还是这个?
set<T> getUnion(set<T> a, set<T> b)
set_union
在名称上是正确的函数。它也可以在vector
上运行,这意味着它可能不如仅set
的功能有效。
我没有追加。追加会破坏原始集合。我想要一个新的集合来表示联合
您可以使用双迭代器std::set::insert
模板:
template <typename T>
std::set<T> getUnion(const std::set<T>& a, const std::set<T>& b)
{
std::set<T> result = a;
result.insert(b.begin(), b.end());
return result;
}
注意:根据一些建议我按值获取其中一个参数的注释,因为我无论如何都需要一个副本,我选择了这个实现来避免不允许RVO,当返回按值获取的参数时不允许RVO。为了更好地处理右值参数,可以提供该函数的重载,接受右值引用并利用move语义。
有std::set_union
该页面的示例使用了向量和数组,所以它非常通用:
输出:// set_union example #include <iostream> // std::cout #include <algorithm> // std::set_union, std::sort #include <vector> // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector<int>::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 it=std::set_union (first, first+5, second, second+5, v.begin()); // 5 10 15 20 25 30 40 50 0 0 v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50 std::cout << "The union has " << (v.size()) << " elements:n"; for (it=v.begin(); it!=v.end(); ++it) std::cout << ' ' << *it; std::cout << 'n'; return 0; }
The union has 8 elements:
5 10 15 20 25 30 40 50
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 为什么我无法更改"set<set>"循环中的值<int>
- 对字符串进行位操作
- 对于set上的循环-获取next元素迭代器
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 在声明中合并两个常量"std::set"(不是在运行时)
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 标准上的 OMP 和并行操作::set<...>::迭代器
- std::set::迭代器和std::set::const_iterator之间是否存在操作差异
- float4::set_wxy(以及其他set-swizzle操作)的更好的SSE2实现
- 对于操作计数()。std::set<void*> 和 std::unordered_set<void*>哪个更快?
- std::set的联合操作