编程语言
首页 > 编程语言> > 集合算法set_difference差集

集合算法set_difference差集

作者:互联网

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Print
{
public:
   void operator()(int i)
   {
      cout << i << endl;
   }
};

int main()
{
   vector<int> v1;
   vector<int> v2;
   for(int i = 0; i < 10; i++)
   {
      v1.push_back(i);
      v2.push_back(i + 5);
   }

   vector<int> vTarget;
   vTarget.resize(v2.size());

   /* v1与v2的差集 */
   vector<int>::iterator it = 
      set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
   for_each(vTarget.begin(), it, Print());

   cout << "-------" << endl;
   
   /* v2与v1的差集 */
   it = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin());
   for_each(vTarget.begin(), it, Print());
   
   return 0;
}
$ ./a.out           
0
1
2
3
4
-------
10
11
12
13
14

注:

  1. 求差集的两个集合必须是有序序列
  2. 目标容器开辟空间,取两个容器较大值
  3. set_difference返回值是差集中最后一个元素的位置

标签:begin,set,vTarget,差集,v1,v2,include,difference
来源: https://www.cnblogs.com/zhangxuechao/p/16537596.html