浅谈STL的set

引言:

c++因为有了STL库所以变得比c语言简单了许多,许多容器不需要自己实现,但是自己必须要熟悉掌握。在STL中有各种你想要的容器及函数,在解决问题中用恰当的容器和函数会有事半功倍的效果。今天就要介绍一下c++最常用的容器之一set的相关操作。

什么是Set:

set即集合,是按照特定顺序存储唯一元素的容器。(里面的元素是唯一的,不论你插入某元素几次)。集合中元素的值不能在容器中修改(元素始终为const),但可以将其插入容器或从容器中删除。 在内部,在所述元件组始终排序以下特定的严格弱排序标准表示通过其内部的比较对象(的类型进行比较)。

如何使用:

#include<set>
using namespace std;

set的容量:

empty()   //是否为空
size()    //返回集合的元素个数
max_size()  //返回集合的最大容量

set的修改:

insert(T a)  //插入元素
erase()   //删除元素
swap(set<T> a)    //交换两个set的元素
clear()    //清除集合里的元素

set的其他操作:

find(T a)   //查找元素a,返回指向a的迭代器,若找不到,返回end()
count(T a)   //查找set里元素a的个数  0或1
lower_bound(T a) //返回小于等于a元素的迭代器
upper_bound(T a) //返回大于等于a元素的下一个元素的迭代器
equal_range(T a) //返回一个pair,返回上限到下限平均数为a 的迭代器

例子:

// set::lower_bound/upper_bound
#include <iostream>
#include <set>

int main ()
{
  std::set<int> myset;
  std::set<int>::iterator itlow,itup;

  for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90

  itlow=myset.lower_bound (30);                //       ^
  itup=myset.upper_bound (60);                 //                   ^

  myset.erase(itlow,itup);                     // 10 20 70 80 90

  std::cout << "myset contains:";
  for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

// set::equal_elements
#include <iostream>
#include <set>

int main ()
{
  std::set<int> myset;

  for (int i=1; i<=5; i++) myset.insert(i*10);   // myset: 10 20 30 40 50

  std::pair<std::set<int>::const_iterator,std::set<int>::const_iterator> ret;
  ret = myset.equal_range(30);

  std::cout << "the lower bound points to: " << *ret.first << '\n';
  std::cout << "the upper bound points to: " << *ret.second << '\n';
//下限指向:30    上限指向:40
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值