C++|STL学习笔记-对STL中关联容器map的进一步认识
发布日期:2021-06-30 10:57:38 浏览次数:2 分类:技术文章

本文共 1998 字,大约阅读时间需要 6 分钟。

关联容器map

key + value 的值

关联容器 = 有序容器(红黑树) + 无序容器(散列表) + hash_map

有序容器中:

map的键值是不允许重复的
multimap的键值是允许重复的
set是一个集合,键值=实值,就是只包含一个值,既是键值也是实值,不允许重复
multiset运行重复

map
底层就是红黑树(平衡排序二叉树)
键值保存,高效访问
插入效率低于链表,因为涉及排序
 

 

下面是一段插入代码,菜鸡一般是这么写的:

#include #include 
using namespace std;void MapConstruct(){ map
mp; mp.insert(pair
(1, 'a')); return;}int main(){ MapConstruct(); getchar(); return 0;}

局部变量结构如下:

 

进价一点点的写法如下代码(稍微有工作经验的人一般是这么写的)

#include #include 
using namespace std;void MapConstruct(){ typedef pair
in_pair; map
mp; mp.insert(in_pair(1, 'a')); //mp.insert(pair
(1, 'a')); return;}int main(){ MapConstruct(); getchar(); return 0;}

局部变量结构如下:

 

遍历一下:

#include #include 
#include
using namespace std;typedef pair
in_pair;void fun(in_pair pr){ cout << pr.first << "\t" << pr.second << endl;}void MapConstruct(){ map
mp; mp.insert(in_pair(1, 'a')); mp.insert(in_pair(2, 'b')); mp.insert(in_pair(3, 'c')); mp.insert(in_pair(4, 'd')); for_each(mp.begin(), mp.end(), fun); return;}int main(){ MapConstruct(); getchar(); return 0;}

运行截图如下:

 

然后,大佬的写法(标准写法,一般是这种写法)

不得不说,大佬和小菜的最大区别就是大佬想得比较周到:

#include #include 
#include
using namespace std;typedef pair
in_pair;typedef pair
::iterator, bool> in_pair_bool;void judgeOk(in_pair_bool pr){ if(pr.second){ cout << "插入成功!" << endl; } else{ cout << "插入失败!" << endl; }}void fun(in_pair pr){ cout << pr.first << "\t" << pr.second << endl;}void MapConstruct(){ map
mp; pair
::iterator, bool> pr; pr = mp.insert(in_pair(1, 'a')); judgeOk(pr); pr = mp.insert(in_pair(2, 'b')); judgeOk(pr); pr = mp.insert(in_pair(3, 'c')); judgeOk(pr); pr = mp.insert(in_pair(4, 'd')); judgeOk(pr); pr = mp.insert(in_pair(1, 'e')); judgeOk(pr); for_each(mp.begin(), mp.end(), fun); return;}int main(){ MapConstruct(); getchar(); return 0;}

运行截图如下:

转载地址:https://it1995.blog.csdn.net/article/details/84096889 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Linux文档阅读笔记-cut与sort的基本用法
下一篇:Linux学习笔记-最基础的常用shell命令

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月15日 16时29分27秒