一、简介
map 是STL中的一个关联容器,和python中的数据类型字典一样,map 类型变量中的元素也是由键-值对组成,没有重复的键。其底层实现是红黑树(非严格意义上的平衡二叉树)
map 中所有元素都是pair,pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值),所有元素都会根据元素的键值自动排序,map/ multimap 属于关联式容器,底层结构是用二叉树实现。
二、 用法
基本用法包括:声明一个map类型的变量、向声明的map变量中插入元素、查找map变量中的元素、删除map变量中的元素、清空map变量中的元素等。
2.1 声明一个map类型的变量
先加入头文件
#include<map>
//map<key类型,value类型> 变量名;
2.2 向map变量中插入数据
(1)用insert函数插入
(2)用给Key赋value的方法插入
map< int, string > student;
/*(1)*/
student.insert(pair(001,"Zhang san"));
student.insert(pair(002,"Li San"));
/*(2)*/
student[001] = "Zhang san";
student[002] = "Li San";
2.3 查找map变量中的某个key
(1) map变量.count(key) 只返回0或1,0表示map变量中不 包含key这个键,1则表示包括
if(student.count(001) == 1)
return student[001];
else
return NULL;
(2) map变量.find(key) 返回一个迭代器,该迭代器指向查询到的这个key元素(存在key这个元素的时候)
find()没找到的时候会指向end()
( 所以说上面的count()用处不大 )
map< int, string > :: iterator it = student.find(001);
return it->second;
map< int, string > :: iterator it = maps.find(1);
if(it != mapStudent.end())
cout<< "Find, the value is " << it->second << endl;
迭代器名称->first 表示迭代器当前指向的元素的key; 迭代器名称->second 表示迭代器当前指向的元素的value;
2.4 删除map变量中的元素、清空map变量
(1)删除元素用erase函数,删除成功返回1,否则返回0
//iterator erase(iterator it); 通过一个条目对象删除
//iterator erase(iterator first,iterator last)删除一个范围
it = student.find(001);
int ans = student.erase(it);
int ans = student.erase(001);
//size_type erase(const Key&key);//通过关键字删除
(2) 清空map变量之间使用clear函数
student.clear();
2.5 map的遍历
//迭代,根据key排序的,我的key是string,故是字典序排序,从a-z
map< string,int >:: iterator it;
for(it = maps.begin(); it != maps.end(); iter++)
cout<< it->first << ' ' << it->second << endl;//输出的是key value值
//数组形式的遍历
int nSize = maps.size();
for(int index = 0; index < nSize; ++index)
cout << maps[index] << endl;
三、相关比较
1、unordered_map与map
(1) 使用前需要引入的头文件不同,前者是 #include< unordered_map > ,后者是 #include < map >
(2) 内部实现机理不同,前者是哈希表,后者是红黑树
(3) map类型变量中元素是自动排序,有序的,而unordered_map类型变量中的元素是无序的
2、make_pair()与pair()
二者的用法示例:
pair <string,double> product1 ("tomatoes",3.25);
pair <string,double> product2;
pair <string,double> product3;
product2.first ="lightbulbs"; // type of first is string
product2.second =0.99; // type of second is double
product3 = make_pair ("shoes",20.0);
cout <<"The price of "<< product1.first <<" is $"<< product1.second <<"\n";
cout <<"The price of "<< product2.first <<" is $"<< product2.second <<"\n";
cout <<"The price of "<< product3.first <<" is $"<< product3.second <<"\n";