Union Operation For std :: set

Are there any functions in the standard library?

set<T> set::union(set<T> other)

Or even that?

set<T> getUnion(set<T> a, set<T> b)

set_union- This is the correct function only in the name. It can also work on vector, which means that it may not be as effective as the set-only function .

I do not add. Adding destroys the original set. I want a new collection representing a union.

+4
source share
2 answers

To do this, you can use a template with two iterators 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, . rvalue, rvalue reverences .

+6

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
+5

Source: https://habr.com/ru/post/1539065/


All Articles