map提供的是一种键值对的容器,里面的数据元素都是成对出现的,即:key-value,在知道 key 的情况下能迅速的找到 value,他们是一一对应的关系。
map 的使用场景:
优点查找起来很快:根据 key 值快速查找记录,查找的复杂度基本是 Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。怎么样快吧?所以,当大家以后的工程中有比较多的使用想快速查找的话可以使用map。
map的头文件和命名空间:
#include <map> //注意,没有 .h
using namespace std; //在 std 标准命名空间中
map的定义及使用
#include <map> //注意,没有 .h
#include<iostream>
using namespace std; //在 std 标准命名空间中
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(); //返回容器的元素个数
bool stud_empty=stud_sex_map.empty(); //检测容器是否为空
cout << "stud_empty=" << stud_empty << endl;
char sex = stud_sex_map[10010];
sex = stud_sex_map[10012]; //这个值会是多少呢?
cout << "sex="<<sex<< endl;
if (stud_sex_map.count(10012) <= 0) //判断容器中是否有某个元素
{
stud_sex_map[10012] = 'f';
}
sex = stud_sex_map[10012];
cout << "sex=" << sex << endl;
system("pause");
return 0;
}
map的删除:
删除的话首当其冲的肯定是erase方法了。erase 方法支持 key 删除和迭代器删除,例如:
stud_sex_map.erase(10010);
stud_sex_map.erase(stud_sex_map.begin());
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;
}
小作业
#include <map> //注意,没有 .h
#include<iostream>
using namespace std; //在 std 标准命名空间中
int main(int argc, char* argv[])
{
map<int, char> stud_sex_map;
stud_sex_map[10010] = 'm'; //赋值
stud_sex_map[10011] = 'f';
stud_sex_map[10012] = 'f'; //赋值
stud_sex_map[10013] = 'm';
stud_sex_map[10014] = 'f'; //赋值
stud_sex_map[10015] = 'm';
int n_size = stud_sex_map.size(); //返回容器的元素个数
for (map<int, char>::iterator itor = stud_sex_map.begin(); itor != stud_sex_map.end(); ++itor)
{
char ch = itor->second;
if (ch == 'f')
{
itor=stud_sex_map.erase(itor);这里很重要需要erase返回下一个迭代器,
//因为删除链表元素之后原链表指针会指向随机地址
itor--;
}
else
{
int key = itor->first;
char ch = itor->second;
cout << "key = " << key << ", value = " << ch << endl;
}
}
//cout << "sex=" << sex << endl;
system("pause");
return 0;
}