在 C++ 中,map
是一个非常重要的标准库容器,它允许以键值对的形式存储数据,并通过键快速查找对应的值。map
是一种有序容器,其内部元素根据键值自动排序。它提供了高效的插入、删除和查找操作,通常是基于红黑树(或其他自平衡二叉搜索树)来实现的。
1. map
的基础概念
map
是 C++ STL(标准模板库)中的一个关联容器,它存储键值对(key-value pair)。每个元素由一个键(key)和一个值(value)组成,并且键是唯一的。
主要特点:
- 键唯一:每个键只能在 map
中出现一次。
- 自动排序:元素根据键值自动排序,默认按升序排列。可以自定义排序规则。
- 高效查找:查找操作的时间复杂度通常是 O(log n),这是因为 map
底层使用了自平衡二叉搜索树(如红黑树)。
2. map的构造函数
(1)空构造函数
map
的空构造函数创建一个空的map
容器,初始化时可以指定自定义的比较函数和分配器。
explicit map(const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
comp:用于比较键的自定义比较函数,默认使用key_compare
。
alloc:自定义的分配器,默认使用allocator_type
。
// 使用默认构造函数创建空的map
map<int, string> myMap;
// 使用自定义比较函数创建map
map<int, string, greater<int>> customMap;
// 使用自定义分配器
map<int, string, less<int>, allocator<pair<const int, string>>> allocMap;
(2)使用分配器构造
该构造函数接受一个自定义分配器来创建一个空的map
。
explicit map(const allocator_type& alloc);
// 使用自定义分配器创建map
map<int, string, less<int>, allocator<pair<const int, string>>> allocMap;
allocMap[1] = "one";
allocMap[2] = "two";
for (auto& pair : allocMap) {
cout << pair.first << ": " << pair.second << endl;
}
(3)区间构造
使用输入迭代器指定的范围来构造map
,并且可以指定比较函数和分配器。
template <class InputIterator>
map(InputIterator first, InputIterator last,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
first和last:指定区间的开始和结束迭代器。
comp和alloc:分别指定自定义的比较函数和分配器,默认为默认构造函数。
vector<pair<int, string>> vec = {
{1, "one"}, {2, "two"}, {3, "three"}};
// 使用区间构造函数创建map
map<int, string> myMap(vec.begin(), vec.end());
for (auto& pair : myMap) {
cout << pair.first << ": " << pair.second << endl;
}
(4)拷贝构造
拷贝构造函数用于根据另一个map
对象创建新对象。
map(const map& x);
map(const map& x, const allocator_type& alloc);
x:要拷贝的map
对象。
map<int, string> originalMap;
originalMap[1] = "one";
originalMap[2] = "two";
// 使用拷贝构造函数创建map
map<int, string> copiedMap(originalMap);
(5)初始化列表构造
通过初始化列表来构造map
,并且可以指定比较函数和分配器。
map(initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
il:初始化列表,用来直接初始化map
中的元素。
// 使用初始化列表构造map
map<int, string> myMap = {
{1, "one"}, {2, "two"}, {3, "three"}};
3. map的迭代器
在 C++ 中,map
是一个关联容器,它将键(key)映射到值(value)。对于 map
容器的迭代操作,可以使用迭代器(iterator
)来访问 map
中的元素。map
的迭代器是双向迭代器,允许你沿着容器进行前向和后向迭代。
1. 基本的迭代方式
map
的迭代器是一个 pair<const Key, T>
类型的对象,其中 first
是键(const Key
),second
是值(T
)。因此,你可以通过迭代器访问每一个元素的键和值。
#include <iostream>
#include <map>
using namespac