您的位置:首页 > 编程语言 > C语言/C++

STL---set基本使用--取集合的交、并、差、对称差

2014-04-08 17:00 267 查看
转自:http://blog.sina.com.cn/s/blog_4c98b9600100az2v.html

set是集合,其底层数据结构是红黑树,STL中set、map均采用红黑树结构作为底层支持,红黑树与AVL树类似,是一种平衡查找树。

set的特性是集合的基本特性:元素唯一性等。

通过algorithm中提供的set_intersection、set_union、set_difference、set_symmetric_difference四个函数,可以方便的实现集合的交、并、差、对称差操作,很实用!

微软帮助文档中对集合(set)的解释: “描述了一个控制变长元素序列的对象(注:set中的key和value是Key类型的,而map中的key和value是一个pair结构中的两个分 量)的模板类,每一个元素包含了一个排序键(sort key)和一个值(value)。对这个序列可以进行查找、插入、删除序列中的任意一个元素,而完成这些操作的时间同这个序列中元素个数的对数成比例关 系,并且当游标指向一个已删除的元素时,删除操作无效。”

而一个经过更正的和更加实际的定义应该是:一个集合(set)是一个容器,它其中所包含的元素的值是唯一的。这在收集一个数据的具体值的时候是有用的。集 合中的元素按一定的顺序排列,并被作为集合中的实例。如果你需要一个键/值对(pair)来存储数据,map是一个更好的选择。一个集合通过一个链表来组 织,在插入操作和删除操作上比向量(vector)快,但查找或添加末尾的元素时会有些慢。

下面是四个函数的标准用法:
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;

int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
set<int> S( a, a + 9 );

int b[] = { 3, 6, 8, 9 };
set<int> S2( b, b + 4 );

set<int>::iterator site;

set<int> Su;
set<int> Si;
set<int> Sd;
set<int> Ssd;

//交集
set_intersection( S.begin(), S.end(),
S2.begin(), S2.end(),
inserter( Si, Si.begin() ) );

//并集
set_union( S.begin(), S.end(),
S2.begin(), S2.end(),
inserter( Su, Su.begin() ) );

//差集
set_difference( S.begin(), S.end(),
S2.begin(), S2.end(),
inserter( Sd, Sd.begin() ) );

//对称差集
set_symmetric_difference( S.begin(), S.end(),
S2.begin(), S2.end(),
inserter( Ssd, Ssd.begin() ) );

site = Si.begin();
cout<<"the intersection of S and S2 is : ";
while( site != Si.end() )
{
cout<< *site <<" ";
++ site;
}
cout<<endl;

site = Su.begin();
cout<<"the union of S and S2 is : ";
while( site != Su.end() )
{
cout<< *site <<" ";
++ site;
}
cout<<endl;

site = Sd.begin();
cout<<"the difference of S and S2 is : ";
while( site != Sd.end() )
{
cout<< *site <<" ";
++ site;
}
cout<<endl;

site = Ssd.begin();
cout<<"the symmetric difference of S and S2 is : ";
while( site != Ssd.end() )
{
cout<< *site <<" ";
++ site;
}
cout<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  stl c++ set 集合操作