本文转载自:VC驿站
https://www.cctry.com/thread-291665-1-1.html
1、什么是 map,他跟 vector 和 list 有什么区别?什么情况下使用 map?
map提供的是一种键值对的容器,里面的数据元素都是成对出现的,即:key-value,在知道 key 的情况下能迅速的找到 value,他们是一一对应的关系。
如下图:第一个值称之为关键字(key),每个关键字只能在map中出现一次,是唯一的;第二个称之为该关键字的对应值:
例如:学校中的学生,用学生的什么信息作为 key 呢?可以用学号,在校的学生学号不可能重复,所以可以用学号作为key,学生的姓名或者学生信息作为value,value可以重复,可以相同,毕竟有重名的情况发生。
2、map 的使用场景:
优点查找起来很快:根据 key 值快速查找记录,查找的复杂度基本是 Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。怎么样快吧?所以,当大家以后的工程中有比较多的使用想快速查找的话可以使用map。
3、map的头文件和命名空间:
#include <map> //注意,没有 .h
using namespace std; //在 std 标准命名空间中
4、map的定义:
一般情况下,都是定义一个空的 map 对象,例如:
map<int, char> stud_sex_map;
定义完了之后再使用,map也是个模板类,所以他也是支持各种类型的。
5、map的使用:
定义完了之后我们就可以开始使用了,例如:
int main(int argc, char* argv[])
{
map<int, char> stud_sex_map;
stud_sex_map[10010] = 'm'; //赋值
stud_sex_map[10011] = 'f';
int n_size = stud_sex_map.size(); //返回容器的元素个数
stud_sex_map.empty(); //检测容器是否为空
char sex = stud_sex_map[10010];
sex = stud_sex_map[10012]; //这个值会是多少呢?
if (stud_sex_map.count(10012) <= 0) //判断容器中是否有某个元素
{
stud_sex_map[10012] = 'f';
}
sex = stud_sex_map[10012];
return 0;
}
6、map的删除:
删除的话首当其冲的肯定是erase方法了。erase 方法支持 key 删除和迭代器删除,例如:
stud_sex_map.erase(10010);
stud_sex_map.erase(stud_sex_map.begin());
7、map的遍历:
因为是 map 不是数组,所以不能用下标来遍历,只能用迭代器来遍历,如下:
for (map<int, char>::iterator itor = stud_sex_map.begin(); itor != stud_sex_map.end(); ++itor)
{
int key = itor->first;
char ch = itor->second;
cout << "key = " << key << ", value = " << ch << endl;
}
8、小作业:
定义一个 map<int, char> 类型的对象:
依次存入以下内容:
10010->'m'
10011->'f'
10012->'f'
10013->'m'
10014->'f'
10015->'m'
之后,使用 for 循环删除map中的value值为 'f' 的元素,并将结果输出出来!
第50课视频教程下载地址: