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

C++集合操作,使用STL的set容器

2016-01-26 10:36 369 查看
Set 是 STL 中给定的容器,会根据设定的排序准则对元素自动排序。

Namespace std {
template <class T, class Compare = less<T>,
Class Allocator = allocator<T> >
Class set;
Template <class T,
Class Compare = less<T>,
Class Allocator = allocator<T> >
Class mutiset;
}


模板的参数 T 为集合元素类型,Compare指定一个仿函数设定集合内的排序规则,Allocator指定空间配置器,默认为STL自带的Allocator。

Set 通常使用的构造函数:

set<Elem> c;  // 一个默认以less<>为排序准则,产生一个空的set,不含任何元素
set<Elem, Op> c // 一个以op为排序准则的不含任何元素的空set


例如:

std::set<int, std::greater<int> > coll;


则定义了一个大的从大到小的排序准则的set coll。

集合上的操作:

count(elem)//返回元素值为elem的元素个数,统计有几个elem元素
find(elem)//返回元素值为elem的第一个元素的迭代器,找不到返回end()
lower_bound(elem)//返回elem的第一个可安插位置
upper_bound(elem)//返回elem的最后一个可安插位置


遍历集合的操作如下:

Typedef set<int, greater<int> > IntSet;
IntSet coll;
IntSet::iterator pos;
For (pos = coll.begin(); pos != coll.end(); ++pos) {
Visit(*pos);
}


set的元素安插和溢出方法:

insert(elem)//安插一份elem副本,返回新元素位置
Insert(pos, elem)//安插一份elem副本,返回新元素位置,pos是搜寻起点用于加速
Insert(beg, end)//将区间[beg; end]内所有元素副本安插到c,无返回值
Erase(elem)//移除与elem相等的所有元素,返回被移除的元素个数
Erase(pos)//移除迭代器pos位置上的元素,无返回值
Erase(beg, end)//移除区间[beg; end]内的所有元素,无返回值、
Clear()//移除全部元素,清空整个容器


ACM代码中用到的举例:

Typedef long long LL;
Set<LL> s;
If (!s.count(x)) { s.insert(x); }


如果在s中没有发现与x等同的元素,则插入x

合并集合操作:

OutputIterator
merge(InputIterator source1Beg, InputIterator source1End,
InputIterator source2Beg, InputItertor source2End,
OutputInterator destBeg)


将元区间[source1Beg, source1End]和[source2Beg, source2End]内的元素合并,使得以[destBeg]起始的目标区间内含有两个元区间的所有元素。

#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())


用以简化输入:

typedef std::set<int> IntSet;
IntSet coll1, coll2, colldest;
merge(ALL(coll1), ALL(coll2), INS(colldest));


取并集操作:

OutPutIterator
set_union(InputIterator source1Beg, InputIterator source1End,
InputIterator source2Beg, InputItertor source2End,
OutputInterator destBeg)

set_union(ALL(coll1), ALL(coll2), INS(colldest));


取交集操作:

OutPutIterator
set_intersection(InputIterator source1Beg, InputIterator source1End,
InputIterator source2Beg, InputItertor source2End,
OutputInterator destBeg)

set_intersection(ALL(coll1), ALL(coll2), INS(colldest));


取差集操作:

OutPutIterator
set_difference(InputIterator source1Beg, InputIterator source1End,
InputIterator source2Beg, InputItertor source2End,
OutputInterator destBeg)

set_difference(ALL(coll1), ALL(coll2), INS(colldest));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  set C++ STL