set和multiset的内部通常是采用平衡二叉树来实现。当放入元素时,会按照一定的排序方法自动排序,默认是按照less<>排序规则来排序。这种自动排序的特性加速了元素查找的过程,但问题是:不可以直接修改set或multiset容器中的元素值,因为这样就违反了元素自动排序的规则。如果想修改一个元素的值,则必须先删除原有的元素,再插入新的元素。
multiset容器的集合并、交、差运算(注意:并集运算的结果)#include "stdafx.h"
#include
#include
#include
using namespace std;
int_tmain(int argc, _TCHAR* argv[])
{
const int N=10;
int a[N] = {4,1,1,1,1,1,0,5,1,0};
int b[N] = {4,4,2,4,2,4,0,1,5,5};
multiset<int> A(a,a+N);
multiset<int> B(b,b+N);
multiset<int> C,D;
cout<<"Set A:";
copy(A.begin(),A.end(),ostream_iterator<int>(cout,""));
cout< cout<<"Set B: "; copy(B.begin(),B.end(),ostream_iterator<int>(cout,"")); cout< cout<<"Union (A and B): "; set_union(A.begin(),A.end(),B.begin(),B.end(),ostream_iterator<int>(cout,"")); cout< cout<<"Union (B and A): "; set_union(B.begin(),B.end(),A.begin(),A.end(),ostream_iterator<int>(cout,"")); cout< cout<<"Intersection (A and B): "; set_intersection(A.begin(),A.end(),B.begin(),B.end(),ostream_iterator<int>(cout,"")); cout< cout<<"Intersection (B and A): "; set_intersection(B.begin(),B.end(),A.begin(),A.end(),ostream_iterator<int>(cout,"")); cout< set_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(C,C.begin())); cout<<"Set C(difference of A and B): "; copy(C.begin(),C.end(),ostream_iterator<int>(cout,"")); cout< set_difference(B.begin(),B.end(),A.begin(),A.end(),inserter(D,D.begin())); cout<<"Set D(difference of B and A): "; copy(D.begin(),D.end(),ostream_iterator<int>(cout,"")); cout< return 0; } 执行结果: 注意并集:最终结果中的相同元素的个数取集合中最多的数目,如此处求并集时0的个数取的是集合A的个数,为两个;5的个数取的是B中的数目,为两个。 因此,两个集合的并、交满足交换率,而差则不满足交换律,符合数学原理。