Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。
下面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学号用int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串,而是采用STL中string来描述),下面给出map描述代码:
一、插入数据
#include
#include
#include
#include
#include
#include 另一种方法
这种方法会覆盖原值,此代码的运行结果为:
2
3
#include
#include
#include
#include
#include
#include 二、map的大小
在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:
Int nSize = mapStudent.size();
三、数据的遍历
以下代码的运行结果为
3 student_three
2 student_two
1 student_one
#include
#include
#include
#include
#include
#include 四、数据的查找(包括判定这个关键字是否在map中出现)
1.用count函数,但是该函数的返回值只有0和1,1为找到,0为没有找到,不能返回要查找的值
2.用find函数
以下代码的运行结果为
find!student_one
#include
#include
#include
#include
#include
#include 五、map的清空
清空用map.clear()函数
m.erase(m.begin(),m.end());//删除的是一个前闭后开的集合
六、检查map是否为空
用函数map.empty()
返回值为true时表示map为空
七、数据的删除
#include
#include
#include
#include
#include
#include 八、排序
对结构体的排序
#include
#include
#include
#include
#include
#include