C++ set_union

原文

set_union可以合并两个排好序的区域成一个set
i.e. 去重
it = set_union(first, first + 5, second, second + 5, v.begin());
first, second都是数组,并且排好序了
v 是 vector,把集合生成到 v里去
然后 返回生成集合末尾的迭代器 it

// set_union example
#include <iostream> // std::cout
#include <algorithm> // std::set_union, std::sort
#include <vector> // std::vector
using namespace std;
int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  vector<int> v(10);                      // 0 0 0 0 0 0 0 0 0 0
  vector<int>::iterator it;
  sort(first, first + 5);     // 5 10 15 20 25
  sort(second, second + 5);   // 10 20 30 40 50
  it = 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
  cout << "The union has " << (v.size()) << " elements:\n";
  for (it = v.begin(); it != v.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';
  return 0;
}

你可能感兴趣的:(C++ set_union)