#include <iostream> #include <map> #include <string> using namespace std; int main() { multimap<string,string>mulmap; multimap<string,string>::iterator p; typedef multimap<string,string>::value_type vt; typedef string s; mulmap.insert(vt(s("Tom "),s("is a student"))); mulmap.insert(vt(s("Tom "),s("is a boy"))); mulmap.insert(vt(s("Tom "),s("is a bad boy of blue!"))); mulmap.insert(vt(s("Jerry"),s(" is a student"))); mulmap.insert(vt(s("Jerry "),s("is a beatutiful girl"))); mulmap.insert(vt(s("DJ "),s("is a student"))); //输出初始化以后的多重映射mulmap: for(p=mulmap.begin();p!=mulmap.end();++p) cout<<(*p).first<<(*p).second<<endl; //检索并输出Jerry键所对应的所有的值 cout<<"find Jerry :"<<endl; p=mulmap.find(s("Jerry ")); while((*p).first=="Jerry ") { cout<<(*p).first<<(*p).second<<endl; ++p; } return 0; }
#include <iostream> #include <map> using namespace std; int main() { map<char,int> map1; map<char,int>::iterator mapIter; //char 是键的类型,int是值的类型 //下面是初始化,与数组类似 //也可以用map1.insert(map<char,int,less<char> >::value_type(''c'',3)); map1['c']=3; map1['z']=4; map1['a']=1; map1['k']=2; for(mapIter=map1.begin();mapIter!=map1.end();++mapIter) cout<<" "<<(*mapIter).first<<": "<<(*mapIter).second; //first对应定义中的char键,second对应定义中的int值 //检索对应于d键的值是这样做的: map<char,int>::iterator ptr; ptr=map1.find('k'); cout<<'\n'<<" "<<(*ptr).first<<" 键对应于值:"<<(*ptr).second; return 0; }