map 简介
C++ 中 map 对象按顺序存储一组值,其中每个元素与一个检索关键字关联,
map 的形式 key -- value , 里面的key 是不允许重复的.
map 同样也是STL中的模板使用的时候 需要先引入 #include <map>
#include <iostream>
#include <string>
using namespace std;
#include <map>
int main()
{
// 创建一个空的map
map<int, string> a;
// 插入值使用value_type
a.insert(map<int, string>::value_type(1, "张三"));
a.insert(map<int, string>::value_type(2, "李四"));
a.insert(map<int, string>::value_type(3, "王二"));
// 插入值使用pair
a.insert(pair<int, string>(4, "赵括"));
// 使用数组插入
a[5] = "张飞";
a.insert(map<int, string>::value_type(3, "李白")); // 不允许key重复,无法插入
cout << a.size() << endl; // 不允许key重复,打印结果为 5
// 遍历map
map<int, string>::iterator it;
for (it = a.begin(); it != a.end(); it++)
{
cout << (*it).first << endl;
cout << (*it).second << endl;
}
}
map 方法说明
函数 | 说明 |
begin | 返回指向map头部的迭代器 |
end | 返回指向map末尾的迭代器 |
empty | 判断map是否为空,为空返回true |
size | 返回map中元素的个数 |
at | 访问元素 |
operator[] | 访问元素 |
insert | 插入元素 |
clear | 清空map |
swap | 交换两个map |
find | 查找一个元素 |
earse | 删除一个元素 |
rbegin | 返回反向迭代器以反向开始 |
rend | 将反向迭代器返回到反向结束 |
cbegin | 将常量迭代器返回到开头 |
cend | 返回常量迭代器结束 |
crbegin | 返回const_reverse_迭代器以反转开始 |
equal_range | 返回特殊条目的迭代器对 |
lower_bound | 将迭代器返回到下限 |
upper_bound
| 将迭代器返回到上限 |
value_comp() | 返回比较元素value的函数 |
demo 练习
#include <iostream>
#include <string>
using namespace std;
#include <map>
int main()
{
// 声明一个set
map<int, string> imap;
// 获取默认set的size
cout << imap.size() << endl;
// 插入值使用value_type
imap.insert(map<int, string>::value_type(1, "张三"));
imap.insert(map<int, string>::value_type(2, "李四"));
imap.insert(map<int, string>::value_type(3, "王二"));
// 插入值使用pair
imap.insert(pair<int, string>(4, "赵括"));
// 使用数组插入
imap[5] = "张飞";
// 获取map size
cout << imap.size() << endl;
// 遍历map
map<int, string>::iterator it;
for (it = imap.begin(); it != imap.end(); it++)
{
cout << (*it).first << endl;
cout << (*it).second << endl;
}
//第二个map的value值
cout << imap.at(2) << endl;
// map 判空
if (imap.empty())
{
cout << "map为空" << endl;
}
else
{
cout << "map不为空" << endl;
}
// 清空map
imap.clear();
return 0;
}