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

一:介绍

map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。

命名空间为std,所属头文件<map> 注意:不是<map.h>

二:常用操作

容量:

修改:

迭代器:

三:存储

    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);

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对<计算机技术网(www.ctvol.com)!!>的支持。如果你想了解更多相关内容请查看下面相关链接

—-想了解C++标准模板库map的常用操作分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/482592.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐