编译环境:VS2008
第一个map程序:
1 #include "stdafx.h" 2 #include <string> 3 #include <map> 4 #include <iostream> 5 6 using namespace std; 7 8 int _tmain(int argc, _TCHAR* argv[]) 9 { 10 map<string,int> word_count; 11 word_count.insert(make_pair("karen",29)); 12 map<string,int>::iterator it = word_count.find("karen"); 13 if(it!=word_count.end()) 14 { 15 cout<<"name="<<it->first<<endl; 16 cout<<"age="<<it->second<<endl; 17 } 18 return 0; 19 }
分析:make_pair("huanghuang",29)等价于pair<string,int>("karen",29),使用make_pair使程序变简单,可读性更好;
make_pair("huanghuang",29)也能这样插入数据:word_count["karen"]=29;
first,second对应于插入数据成员:first对应karen,second对应29。