实践如下:
#include <iostream> #include <map> #include <string> #include <typeinfo> using namespace std; int main() { cout << "Map 测试" << endl; //int i =1; string name("jack"); pair<int, string> pair1(1, name); pair<int, string> pair2(2, "老张"); map<int, string> map1; map1.insert(pair1); map1.insert(pair1); map1.insert(pair2); map<int, string>::iterator it; for (it = map1.begin(); it != map1.end(); it++) { cout << (*it).first << "->" << (*it).second << endl; } pair<string, string> pair21("张三", "张三"); pair<string, string> pair22("老张", "老张"); map<string, string> map2; map2.insert(pair21); map2.insert(pair21); map2.insert(pair22); map<string, string>::iterator it2; for (it2 = map2.begin(); it2 != map2.end(); it2++) { cout << (*it2).first << "->" << (*it2).second << endl; } map2.erase("张三"); cout << "再次遍历" << endl; for (it2 = map2.begin(); it2 != map2.end(); it2++) { cout << (*it2).first << "->" << (*it2).second << endl; } map2.insert(pair<string, string>("老张2", "老张2")); cout << "再次遍历2" << endl; for (it2 = map2.begin(); it2 != map2.end(); it2++) { cout << (*it2).first << "->" << (*it2).second << endl; } cout << "测试结束" << endl; return 0; }