C++ STL set 的基本用法
来源:互联网 发布:java使用odata 编辑:程序博客网 时间:2024/05/29 19:35
set的基本用法
这个程序展示了一些set的最基本的功能:
#include<cstdio>#include<iostream>#include<set>using namespace std;int main(){ set<int>norm_set; //定义一个集合 for(int i=10;i>=1;i--) norm_set.insert(i); //向集合中插入一个元素 printf("size of the set is %d\n",norm_set.size()); //计算集合中元素个数 for(set<int>::iterator it=norm_set.begin();it!=norm_set.end();it++) { //遍历集合元素 //set<int>::iterator 集合的指针迭代器类型 //norm_set.begin() 集合的起始迭代器 (闭区间) //norm_set.end() 集合的末尾迭代器 (开区间) //it++ 把迭代器挪到下一个元素身上 int x=*it; //迭代器的用法和指针一样 printf("%d ",x); }printf("\n"); set<int>::iterator ite=norm_set.find(10); //返回一个元素的迭代器 norm_set.erase(5); //删除集合中某元素 norm_set.erase(ite); //既可以删除特定值对应的元素,也可以删除迭代器指定的元素 if(norm_set.find(5)==norm_set.end()) printf("value 5 is not exist!\n"); else printf("value 5 is exist!\n"); //如果一个元素不存在于集合中,那么find操作返回集合的尾迭代器 (开区间) //可以用这种方法判断一个元素是否存在与这个集合中 if(norm_set.count(3)==0) printf("value 3 is not exist!\n"); else printf("value 3 is exist!\n"); //count用于计算某一个元素在多重集中出现的次数 //在map和普通set中也可用于判断一个元素是否存在 while(!norm_set.empty()) { //empty 用于判断一个集合是否为空 set<int>::iterator it=norm_set.begin(); printf("%d ",*it); norm_set.erase(it); } return 0;}
这是这个程序的运行结果:
定义以结构体为元素的集合:
#include<cstdio>#include<iostream>#include<algorithm>#include<set>#include<cmath>using namespace std;struct Point{double x,y;}; //表示平面上的一个点Point make_point(double x,double y){Point ans={x,y};return ans;}bool fequ(double a,double b){return fabs(a-b)<1e-6;} //考虑精度误差bool operator<(Point A,Point B) //为结构体重载小于号 { if(fequ(A.x,B.x)) return A.y<B.y; return A.x<B.x;}struct cmp //定义比较结构体(结构体里面重载一个括号) { bool operator()(Point A,Point B){return A<B;}};int main(){ set<Point,cmp>struct_set; //定义一个点集(结构体集合) for(int i=1;i<=100;i++) for(int j=1;j<=100;j++) struct_set.insert(make_point(i,j)); Point A=make_point(101,101),B=make_point(5,10); if(struct_set.find(A)==struct_set.end()) printf("A(101,101) point not exist!\n"); else printf("A(101,101) point exist!\n"); if(struct_set.find(B)==struct_set.end()) //这回别用count了,我不知道怎么写 printf("B(5,10) point not exist!\n"); else printf("B(5,10) point exist!\n"); //...其他操作与前文相同 return 0;}
阅读全文
0 0
- STL的set基本用法
- STL之Set:Set的基本用法
- STL之Set:Set的基本用法
- STL之Set:Set的基本用法
- STL set基本用法
- 【STL】set map的基本用法
- 【STL】map和set的基本用法
- STL之set的基本用法
- C++ STL set 的基本用法
- [C++::STL]之set的用法
- STL set的用法
- stl set的用法
- set的用法 STL
- STL中map,set的基本用法示例
- c++STL pair的基本用法
- STL基本用法【vector】【map】【string】【set】
- C++/STL关联容器-集合-multiset&set的用法
- STL set的基本操作
- 一些友好的CLI工具
- 深度学习识别 验证码
- 03-树2 List Leaves
- Java之String类、StringBuffer类和StringBuilder类
- 【BZOJ4538】【HNOI2016】网络
- C++ STL set 的基本用法
- Hadoop下TreeMap的使用
- Spring入门(Schema-based AOP其三)
- 690 leetcode employee importance
- Unity使用ECS架构entitas实现ui响应及回放系统
- 如何保证cookie的安全性
- codevs1074:[NOI2001] 食物链(并查集)
- 两个链表的第一个公共结点java实现
- 【HDU】 2709