常用STL工具整理
STL好啊!
Vector
#include<vector> vector<int> v vector<int>::iterator it for(it=v.begin();it!=v.end();it++) cout<<*it<<endl;
v.push_back(x) v.pop_back(x) v.erase(it)//删除后,原下标下一个向前补齐 v.clear() v[x]//支持下标查询,但不会判断是否越界 v.begin() v.end() v.empty() e.size()
Set
#include<set> set<int> s; multiset<int> s; struct node{ ...; }; set<node> s; bool operator<(const node &x,const node &y){ return x.a<y.a; } s.empty() s.size() s.begin() s.end() s.clear() s.count(x)//O(log n) 返回值为 x 的元素个数 for(set<int>::iterator it=s.begin();it!=s.end();it++) cout<<*it; s.insert(x) s.erase(it) s.erase(x) //注意在multiset中s.erase(x)会删除所有值为x的元素 s.find(x) //查找值为x的元素,并返回该元素的迭代器 //若不存在,返回s.end() if(s.find(x)!=s.end()) cout<<"Have found!"<<endl; s.lower_bound()//>= s.upper_bound()//> //返回的都是迭代器 //特殊地,对于比set中最大元素大的元素,返回s.end()
Map
#include<map> map<string,int> m; struct node{ ... }; map<node,int> m; bool operator<(const node &x,const node &y){ return x.a<y.a; } m[key]//返回key对应的value,可以赋值 //若不存在,将新建一个二元组(key,0),返回0 m.empty() m.clear() m.count(x)//返回key为x的元素个数,O(log n) for(map<string,int>::iterator it=m.begin();it!=m.end();it++) m.find(x)//查找key为x的二元组,若不存在返回m.end() if(m.find(x)!=m.end()) cout<<"Have found!"<<endl; m.insert(make_pair(key,value))//插入时若已存在重复的key,本次插入无效 m.erase(make_pair(key,value)) m.erase(it)