algorithm(set)
来源:互联网 发布:淘宝怎么打印发货单 编辑:程序博客网 时间:2024/06/15 11:25
set是一个内部自动有序并且不含重复元素的容器。可以用set保留元素本身而不用考虑它的个数;
加入set之后客户已实现自动排序;
首先要想使用set就要加上set头文件:#include<set>;
还需要在头文件下面加上一句:using namespace std;
1、set的定义:
set<typename> name;
其定义和vector基本一样,或者说大部分STL都是这样定义的,这里面的typename可以是任何基本类型,
也可以是STL标准容器:vector,set,queue等;
2、set容器内元素的访问:
set只可以通过迭代器(iterator)访问:
set<typename>::iterator it;
这样就可得到迭代器it,并且可以通过*it来访问set内的元素;
#include<iostream>#include<algorithm>#include<set>#include<cstdio>using namespace std;int get_sum(int input){int sum=0;while(input>0){sum+=input%10;input/=10;}return sum;}int main(){#ifdef ONLINE_JUDGE#elsefreopen("in.txt","r",stdin);freopen("out.txt","w",stdout);#endifset<int> ans;int n;cin>>n;int input;for(int i=0;i<n;i++){cin>>input;ans.insert(get_sum(input));}cout<<ans.size()<<endl;set<int>::iterator it=ans.begin();for(;it!=ans.end();it++){if(it==ans.begin()){cout<<*it;}else{cout<<" "<<*it;}}cout<<endl;return 0;}输入:
8
123 899 51 998 27 33 36 12
输出:
4
3 6 9 26
由输出可看:按照递增排序的,并自动去除重复元素(题目来自pat乙级1064)
3、set常用函数:(n是set内元素的个数)
insert(x);
将x插入到set容器中,并自动递增排序和去重,时间复杂度O(logn);
find(value);
返回set中对应值为value的迭代器(迭代器可以看做一种类似于指针的东西),时间复杂度O(logn);
erase():
用法有两种,一个是删除单个元素,一个是删除一个区间内的所有元素;
size();
可以用来获得set内的元素的个数;
clear();
用来清空set内部所有元素;
注:set最主要作用是自动去重,并按照升序排序,因此碰到需要去重但是却不方便直接开数组的情况可以用set;
0 0
- algorithm(set)
- (Algorithm)不相交集(Disjoint-set)
- Algorithm学习笔记 --- Set Definition(单调队列)
- Set Partition Algorithm(集合划分算法)
- Independent set of tree with greedy algorithm
- Disjoint-Set Data Structure (Union Find Algorithm)
- K Centers Problem | Set 1 (Greedy Approximate Algorithm)
- 算法(Algorithm)
- Algorithm.Find(查找)
- Algorithm.Induction(归纳法)
- 算法(Algorithm)
- Densenet(Algorithm+Code)
- Algorithm
- Algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- Spring+mybaits+springmvc练习
- c++实验3—多分数段函数求值
- 摘自w3school的html标签内容——框架标签
- bootstrap仿百度输入框智能提示(提示信息存在于数据库中)
- Linux shell I/O 重定向
- algorithm(set)
- MySql修改数据库编码为UTF8
- IIS7.5 HTTP 错误 500.19
- 分别求1+2+3+.....+n 和 1*2*3*......*n递归
- Docker的数据卷和数据卷容器
- Django-HttpResponse返回models对象
- FastDFS在.Net平台上的使用
- java.math.BigInteger cannot be cast to java.lang.Long
- Python3的循环