温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中如何使用map标准模板库

发布时间:2022-04-14 17:24:21 来源:亿速云 阅读:179 作者:zzz 栏目:编程语言

本篇内容主要讲解“C++中如何使用map标准模板库”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中如何使用map标准模板库”吧!

一:介绍

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

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

二:常用操作

容量:

  • a.map中实际数据的数据:map.size()

  • b.map中最大数据的数量:map.max_size()

  • c.判断容器是否为空:map.empty()

修改:

  • a.插入数据:map.insert()

  • b.清空map元素:map.clear()

  • c.删除指定元素:map.erase(it)

迭代器:

  • a.map开始指针:map.begin()

  • b.map尾部指针:map.end() 注:最后一个元素的下一个位置,类似为NULL,不是容器的最后一个元素

三:存储

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

到此,相信大家对“C++中如何使用map标准模板库”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI