集合算法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返回值是差集中最后一个元素的位置
posted @ 2022-07-31 17:18  thomas_blog  阅读(209)  评论(0编辑  收藏  举报