std set_union总是首先采用共同的元素

时间:2017-04-19 15:18:30

标签: c++ stl set-union

当两个数组中有共同元素时,std set_union是否总是从第一个数组中获取这些共同元素?从下面的代码片段可以看出它始终从第一个数组中选择常用元素,但是这有保证吗?如何从第二个选择。

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

struct Foo
{
  Foo(int i, const std::string& n): id(i), name(n){}
  int id;
  std::string name;
};

bool comp(const Foo& first, const Foo& second)
{
  return first.id < second.id;
}

int main()
{
  Foo foo5A(5, "A");
  Foo foo10A(10, "A");
  Foo foo15A(15, "A");
  Foo foo20A(20, "A");
  Foo foo25A(25, "A");
  Foo fooA[] = {foo5A, foo10A, foo15A, foo20A, foo25A};

  Foo foo10B(10, "B");
  Foo foo20B(20, "B");
  Foo foo30B(30, "B");
  Foo foo40B(40, "B");
  Foo foo50B(50, "B");
  Foo fooB[] = {foo10B, foo20B, foo30B, foo40B, foo50B};

  std::vector<Foo> fooUnion;
  std::set_union(fooA, fooA+5, fooB, fooB+5, std::back_inserter(fooUnion), comp);

  for(const auto& f : fooUnion)
  {
    std::cout << f.id << ":" << f.name << std::endl;    
  }  
}

输出结果为:

5:A
10:A
15:A
20:A
25:A
30:B
40:B
50:B

1 个答案:

答案 0 :(得分:1)

是的,它来自参考here

  

两个集合的并集由任一集合中存在的元素或两者组成。第二个范围中具有第一个范围中的等效元素的元素不会复制到结果范围。

如果你想从第二个( fooB )中选择它,你可以交换参数:

std::set_union(fooB, fooB+5, fooA, fooA+5, std::back_inserter(fooUnion), comp);