#include

求交集:

set_intersection(first1,last1,first2,last2, result)

求集合差:set_difference(first1,last1,first2,last2, result)

合并两个集合:set_union(first1,last1,first2,last2, result)

上述所传递的容器必须是排序的

1
2
3
4
5
sort(vm.begin(), vm.end());
sort(vn.begin(), vn.end());
vector<int> result;
set_intersection(vm.begin(), vm.end(), vn.begin(), vn.end(), inserter(result, result.begin()));
result.erase(unique(result.begin(), result.end()), result.end());//这是由于vector元素可能存在重复,需要去重

set_intersection实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result){
while (first1!=last1 && first2!=last2)
{
if (*first1<*first2) ++first1;
else if (*first2<*first1) ++first2;
else {
*result = *first1;
++result; ++first1; ++first2;
}
}
return result;