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

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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值