c++ - 在 C++ 中使用 vector 设置并集算法

标签 c++ algorithm vector union-find

在这个问题中我只使用了std::vector,我可以保证每个 vector 中没有重复项(但每个 vector 中没有任何顺序)。如何合并我拥有的 vector ?

例子:

如果我有以下 vector ...

1
1
3 2
5
5 4
2
4
4 2

合并后我应该只剩下两个 vector :

1
2 3 4 5

同样,我只使用 vector ,std::set 是不允许的。

最佳答案

您可以使用 std::set_union 算法。

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

引用:http://www.cplusplus.com/reference/algorithm/set_union/

关于c++ - 在 C++ 中使用 vector 设置并集算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15916856/

相关文章:

c++ - C/C++ 中的地址偏移量是否在编译时解析?

string - 给定范围内最长平衡括号链的长度

c++ - 如何将具有一定数量单词的 vector<string> 的输出读取到一行?

c++ - 适用于 Windows 7 的 OpenGL

C++:迭代 STL 容器的正确方法

algorithm - 线性搜索优化 - 减少计算次数

c++ - 为什么在分配/取消分配一些小对象后内存不可重用?

c++ - 当我洗牌时,指向 vector 中元素的指针会发生什么?

c++ - 私有(private)类型的模板特化

algorithm - 通过数组的最小异或路由的可能线性时间算法