C++ set容器
来源:互联网 发布:编程pmc 编辑:程序博客网 时间:2024/05/21 20:26
set集合容器:
调用头文件:
#include<set>
using namespace std;
详细用法(部分):
set<int> t ------ 定义一个int类型的容器,注意set里的每个元素只会出现1次
t.insert(k) ------ 插入元素k,多次插入同一个元素后面无效
t.count(k) ------ 判断元素k是否在容器内
t.erase(k) ------ 删除元素k,若不存在则删除无效
t.clear() ------ 清空容器
t.size() ------ 返回容器现有元素个数
t.empty() ------ 判断容器是否为空
想遍历set里的元素或进行进一步修改,必须定义对应迭代器,以下三种定义方法(迭代器类似于指针)
set<int>::iterator it ------ 定义正向迭代器
set<int>::reverse_iterator rit; ------ 定义反向迭代器
auto it = t.begin(); ------ 因为t.begin()返回正向迭代器,所以it自动被定义为正向迭代器,可适应其他所有操作
以下需要迭代器的操作:
t.begin() ------ 返回set中第一个元素,类型为正向迭代器
t.rbegin() ------ 返回set中最后一个元素,类型为反向迭代器
t.end() ------ 返回set中最后一个元素,类型为正向迭代器
t.rend() ------ 返回set中第一个元素,类型为反向迭代器
t.find(k) ------ 寻找k,若找到返回对应的迭代器,否则返回end();
t.insert(a, b) ------ 插入指针[a, b)之间的元素,已有元素不会再次插入
t.erase(it) ------ 删除迭代器it对应的元素
t.erase(l, r) ------ 删除迭代器[l, r)之间的元素
lower_bound(k) ------ 返回第一个大于等于k的元素的迭代器
upper_bound(k) ------ 返回第一个大于k的元素的迭代器
#include<stdio.h>
#include<set>
using namespace std;
set<int> t;
int main(void)
{
t.insert(5);
t.insert(3);
t.insert(8);
t.insert(9);
t.insert(12);
printf("the size is %d\n", t.size());
printf("%d %d\n", t.count(5), t.count(-1)); //运行结果:1 0
set<int>::iterator it;
for(it=t.begin();it!=t.end();it++) //运行结果:3 5 8 9 12
printf("%d ", *it);
printf("\n");
set<int>::reverse_iterator rit;
for(rit=t.rbegin();rit!=t.rend();rit++) //运行结果:12 9 8 5 3
printf("%d ", *rit);
printf("\n");
auto a = t.begin();
auto b = t.begin();
b++;
t.erase(a,b);
for(it=t.begin();it!=t.end();it++) //运行结果:5 8 9 12
printf("%d ", *it);
printf("\n");
a = t.lower_bound(6);
b = t.upper_bound(8);
printf("%d %d\n", *a, *b); //运行结果:8 9
return 0;
}
- C++--STL---set容器
- C++---set容器的用法
- c++set和multiset容器
- c++STL Set集合容器
- C++STL之set容器
- 【C/C++】关联容器pair map set
- C++STL练习<queue> <set>容器使用
- C++STL之关联容器【map】【set】
- C++STL之Set集合容器
- C/C++ set容器的基本操作
- C/C++ set容器的基本操作
- 大爱C++——set容器
- 关于C++set容器的使用
- C++::STL::容器类::set/multiset
- C++STL中的set容器和map容器
- 【c++】vector容器&set容器的基本操作
- set容器
- set容器
- Linux学习-Centos 常用命令整理
- xss攻击入门
- POJ 3069 Saruman's Army(贪心)
- 浙江中医药大学暑期训练测试赛八E
- hdu 3694 Fermat Point in Quadrangle (数学)
- C++ set容器
- 基于vector的邻接表解决最短路稀疏图的问题
- sessionScope前端权限限制
- 猜数字游戏
- Vue2.0开发仿豆瓣电影WebApp
- oracleday05(查询 空 日期)
- STL中的find,find_if函数(对类、容器(vector、list)进行查找)
- JS截取字符串常用方法详细整理
- JQuery的ajax()的data的参数类型