map提供的是一种键值对的容器,里面的数据元素都是成对出现的,即:key-value,在知道 key 的情况下能迅速的找到 value,他们是一一对应的关系。
文章目录
map 的使用场景:map的头文件和命名空间:map的定义及使用map的删除:map的遍历:小作业
map 的使用场景:
优点查找起来很快:根据 key 值快速查找记录,查找的复杂度基本是 Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。怎么样快吧?所以,当大家以后的工程中有比较多的使用想快速查找的话可以使用map。
map的头文件和命名空间:
#include <map>
using namespace std
;
map的定义及使用
#include <map>
#include<iostream>
using namespace 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>
#include<iostream>
using namespace 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
);
itor
--;
}
else
{
int key
= itor
->first
;
char ch
= itor
->second
;
cout
<< "key = " << key
<< ", value = " << ch
<< endl
;
}
}
system("pause");
return 0;
}