STL中的set集合容器进行集合运算:并、交、差实例
集合容器的集合运算:并、交、差:
#include "stdafx.h"
#include <iostream>
#include <set>
#include <algorithm> //集合运算:并、交、差需要包含该头文件
using namespace std;
structltstr
{
bool operator()(const char* s1,const char* s2)const
{
return strcmp(s1,s2)<0; //由小到大排序
//return strcmp(s1,s2)<0; //由大到小排序
}
};
int_tmain(int argc, _TCHAR* argv[])
{
const int N = 6;
const char* a[N] = {"isomer","ephemeral","prosaic","nugatory","artichoke","serif"};
const char* b[N] = {"flat","this","artichoke","frigate","prosaic","isomer"};
set<const char*,ltstr>A(a,a+N);
set<const char*,ltstr> B(b,b+N);
set<const char*,ltstr>C;
set<const char*,ltstr>D;
cout<<"Set A:";
copy(A.begin(),A.end(),ostream_iterator<constchar*>(cout," "));
cout<<endl;
cout<<"Set B:";
copy(B.begin(),B.end(),ostream_iterator<constchar*>(cout," "));
cout<<endl;
cout<<"Union: ";
//set_union函数需要#include <algorithm>
set_union(A.begin(),A.end(),B.begin(),B.end(),ostream_iterator<constchar*>(cout," "),ltstr());
cout<<endl;
cout<<"Intersection: ";
set_intersection(A.begin(),A.end(),B.begin(),B.end(),ostream_iterator<constchar*>(cout," "),ltstr());
cout<<endl;
cout<<"Set C (difference of A and B):";
set_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(C,C.begin()),ltstr());//从A中减去B包含的元素
copy(C.begin(),C.end(),ostream_iterator<constchar*>(cout," "));
cout<<endl;
cout<<"Set D (difference of B and A):";
set_difference(B.begin(),B.end(),A.begin(),A.end(),inserter(D,D.begin()),ltstr());//从B中减去A包含的元素
copy(D.begin(),D.end(),ostream_iterator<constchar*>(cout," "));
cout<<endl;
return 0;
}
运行结果: