std::set的联合操作

Union Operation For std::set

本文关键字:操作 set std      更新时间:2023-10-16

标准库中没有这样的函数吗?

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