概述
std::map
是一个模板类,定义在头文件 <map>
中:
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>
> class map;
std::map
是一种有序关联容器,它包含具有唯一键的键值对。- 键之间以比较函数
Compare
排序。 - 搜索、移除和插入操作拥有对数复杂度。
- map 通常实现为红黑树。
std::map
的迭代器以升序迭代各键,此升序由构造时所用的比较函数定义。就是说,给定
m
,一个std::map
it_l
和it_r
,m
的可解引用迭代器,且it_l < it_r
,
则 m.value_comp()(*it_l, *it_r) == true
(使用默认比较函数时为从小到大排序)。
标准库使用比较概念时,均用等价关系来确定唯一性。不精确地说,如果两个对象 a
与 b
相互比较均不小于对方:!comp(a, b) && !comp(b, a)
,那么认为它们等价。
map中的成员类
map类中的成员函数
map类中的非成员函数
成员函数begin与cbegin
std::map<Key,T,Compare,Allocator>::begin
, std::map<Key,T,Compare,Allocator>::cbegin
函数原型:
函数功能:返回指向 map 首元素的迭代器。如果 map 为空,那么返回的迭代器等于 end()
。
函数说明:
- 参数:无参数;
- 返回值:指向首元素的迭代器;
- 复杂度:常数:
- 注解:libc++ 将 cbegin() 向后移植到 C++98 模式。
函数使用示例:
#include <iostream>
#include <map>
int main()
{
std::map<int, float> num_map;
num_map[4] = 4.13;
num_map[9] = 9.24;
num_map[1] = 1.09;
// 调用 num_map.begin() 和 num_map.end()
for (auto it = num_map.begin(); it != num_map.end(); ++it)
std::cout << it->first << ", " << it->second << '\n';
}
输出:
1, 1.09
4, 4.13
9, 9.24
使用自定义比较函数的示例
#include <cmath>
#include <iostream>
#include <map>
struct Point {
double x, y; };
// 比较两个 Point 指针的 x 坐标。
struct PointCmp
{
bool operator()(const Point* lhs, const Point* rhs) const
{
return lhs->x < rhs->x;
}
};
int main()
{
// 注意尽管 x 坐标乱序,亦将按照递增的 x 坐标迭代 map。
Point points[3] = {
{
2, 0}, {
1, 0}, {
3, 0}};
// mag 是发送结点地址到其在 x-y 平面中长度的 map
// 尽管键为指向 Point 的指针,我们希望按照点的 x 坐标而非点的地址为 map 赋序。
// 通过用 PointCmp 类的比较方法进行。
std::map<Point*, double, PointCmp> mag(
{
{
points, 2}, {
points + 1, 1}, {
points + 2, 3}}
);
// 从 0 到长度更改每个 y 坐标
for (auto iter = mag