版权声明: https://blog.csdn.net/Wang_Jiankun/article/details/82499160
C++ 标准库类型 map
一、map 的使用与定义
1、使用 map 类型
标准库类型 map 就是字典,每个元素是一组键值对。使用二叉搜索树实现。
- 关键字是互异的,不存在相同的键值。
- map 内部的元素通常按照其 Key 值排序,且排序方式是根据某种明确、严格的弱排序标准进行的,这种排序标准是由 map 内部的比较对象(即 map::key_comp)指定的。
#include <map>
2、定义和初始化 set 对象
- map 是类模板,实例化时必须指定键和值的类型。
- 通常声明一个空的字典,之后再往里添加元素。
// 声明一个空的字典,键为int,值为string
map<int,string> m;
二、map 操作
1、map 类成员函数
clear ():清除 map 中所有元素
erase ():删除 map 中指定的元素
insert ():添加 pair 类型的元素
find ():在 map 中查找元素,返回迭代器
begin():起始位置迭代器
end(): 终点位置迭代器
empty() :如果map为空则返回 true
size():返回map中元素的个数
key_comp() :返回key排序规则的函数
2、实例
#include <map>
map<int,string> m;
// 插入insert(),三种方式
m.insert(pair<int, string>(1, "one"));
m.insert(map<int, string>::value_type (1, "one"));
m[1] = "one"
// 删除erase(),三种方式
m.erase("r123"); // 按键删除
m.erase(iter) // 按迭代器删除
m.erase(m.begin(), m.end()); // 按迭代器范围删除
// 查找find (),按键查找值。有则返回该元素的迭代器,否则返回尾迭代器
// 用first访问std::pair的第一个成员(Type1),second访问第二个成员 (Type2)
iter = m.find(1);
if(iter != m.end())
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"not find"<<endl;
// 遍历map
map<int,string>::iterator it = m.begin()
for (it; it != m.end(); it++)
cout<<it->first<<":"<<it->second<<endl;
// map 默认是按key排序的。按值排序如下
#include <algorithm>
typedef pair<int, string> PAIR
int cmp(const PAIR &x, const PAIR &y)
{
return x.second > y.second;
}
sort(m.begin(), m.end(), cmp)