##map 数据结构常见用法
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include<iostream> #include<map> #include<iterator> using namespace std; typedef map<int,string,less<int> >M_TYPE;//less greater 都是算子,针对键值来的 默认排序其实也就是key值的升序 ,也就是less<int> typedef M_TYPE::iterator M_IT; int main() { M_TYPE Map; Map[1]="no.1"; Map[2]="no.2"; Map[3]="no.3"; Map[4]="no.4"; Map[5]="no.5"; M_IT it=Map.find(2); cout<<"map[2]是"<<it->second<<endl; Map.insert(make_pair(2,"new no.2"));//不能改变已有的,可以添加没有的 Map.insert(make_pair(6,"no.6")); Map.insert(pair<int,string>(7,"no.7")); cout<<"新的map[2]是"<<it->second<<endl; M_IT is=Map.find(2); cout<<"新的map[2]是"<<is->second<<endl; it->second="new new no.2";//可以修改原有的 cout<<"最新的map[2]是"<<it->second<<endl; for(M_IT tt= Map.begin();tt!=Map.end();tt++) { cout<<tt->second<<endl; } Map.erase(2); cout<<endl; for(M_IT tt= Map.begin();tt!=Map.end();tt++) { cout<<tt->second<<endl; } cout<<endl; M_IT id=Map.find(5); Map.erase(id); for(M_IT tt= Map.begin();tt!=Map.end();tt++) { cout<<tt->second<<endl; } return 0; }
|
水果hdu1263 map内部嵌套用法 简单例题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include<iostream> #include<cstring> #include<map> #include<string> using namespace std; typedef map<string,map<string,int> > MA_P; typedef map<string,int> Ma_P; int main() { int n; cin>>n; while(n--) { int o; cin>>o; string s1,s2; int k; map<string,map<string,int> >q; for(int i=0;i<o;i++) { cin>>s1>>s2>>k; q[s2][s1]+=k;//亲测双重map只能这样用,不能用q.insert(make_pair(s2,make_pair(s1,k)))和pair(XX); } for(MA_P::iterator i=q.begin();i!=q.end();i++) { cout<<i->first<<endl; for(Ma_P::iterator t=i->second.begin();t!=i->second.end();t++) { cout<<" |----"<<t->first<<"("<<t->second<<")"<<endl; } } if(n>0) cout<<endl; } return 0; }
|
set数据结构常见用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include<iostream> #include<string> #include<set> using namespace std; int main() { set<string>strset; set<string>::iterator it; strset.insert("aa"); strset.insert("bb"); strset.insert("cc"); strset.insert("dd"); for(it=strset.begin();it!=strset.end();it++)//set默认排序为升序,也就是less { cout<<*it<<endl; } it=strset.begin(); cout<<"set的第一个元素"<<*it<<endl; it=strset.end(); it--; cout<<"set的最后一个元素"<<*it<<endl; cout<<strset.empty()<<endl; cout<<strset.size()<<endl; cout<<strset.max_size()<<endl;//容器可能包含的元素最大个数 return 0; }
|