#include<iostream> #include<string> #include<map> using namespace std; //map <T1,T2> m; map<string,int>a; void Insert(){ //两种插入方法 //一: a.insert(pair<string,int>("Tom",1));//("Tom" -> 1) a.insert(pair<string,int>("Jone",2));//("Tom" -> 1,"Jone" -> 2) a.insert(pair<string,int>("Tom",2));//("Tom" -> 2,"Jone" -> 2) /* pair是一个元组,配套insert使用, 未知上述插入法优点在哪,所以 个人更推荐下面那种简便方法, 如日后知晓,就另行修改 */ //二: a["Mary"]=4;//("Tom" -> 1,"Jone" -> 2,"Mary" -> 4) a["Mark"]=3;//("Tom" -> 1,"Jone" -> 2,"Mary" -> 4,"Mark" -> 3) } void Find_Key(){ //检查关键字是否映射过 yes ? 1 : 0 cout<<a.count("Mary")<<endl; } void Travel(){ //简单来说,还是关于迭代器的运用 for(map<string,int>::iterator it=a.begin();it!=a.end();it++){ cout<<it->first<<"is in class "<<it->second<<endl; } } void General_function(){ //清空 a.clear(); //判空 a.empty(); //大小 a.size(); } int main(){ Insert(); Find_Key(); Travel(); return 0; }
来源:https://www.cnblogs.com/yifeianyi/p/12188720.html