C++标准模板库map的常用操作

2020-01-06 20:02:47刘景俊


  map<int, string> map1;
  //方法1:
  map1.insert(pair<int, string>(2, "beijing"));
  //方法2:
  map1[4] = "changping";
  //方法3:
  map1.insert(map<int, string>::value_type(1, "huilongguan"));
  //方法4:
  map1.insert(make_pair<int, string>(3, "xierqi"));

四:遍历


for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
 {
 cout << it->first << ":" << it->second << endl;
 }

五:查找


 string value1 = map1[2];
 if (value1.empty())
 {
 cout << "not found" << endl;
 }
 //方法2
 map<int, string>::iterator it = map1.find(2);
 if (it == map1.end())
 {
 cout << "not found" << endl;
 }
 else
 {
 cout << it->first << ":" << it->second << endl;
 }

六:修改


 //修改数据
 map1[2] = "tianjin";

七:删除


 //方法1
 map1.erase(1);
 //方法2
 map<int, string>::iterator it1 = map1.find(2);
 map1.erase(it1);

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到C++教程频道。