C++:std::map
std::map<Key, T> 按键的比较顺序存放键值对。每组等价的键只占一项,既能按键查找,也能按顺序遍历结果。
别名 · 有序映射、有序字典
键如何判定为同一项 #
比较器定义键的顺序。对键 a、b,如果 comp(a, b) 和 comp(b, a) 都为假,容器把两者视为等价。在常见的 std::map<std::string, int> 中,键使用字符串的默认顺序。按键查找和普通的单项插入具有对数复杂度。
按字母序统计词频 #
operator[] 在键缺失时插入该键及值初始化的映射值。对于 int,这个初值是零。下面让每个输入词对应的计数加一,随后使用范围 for按键顺序输出 apple 2 和 pear 1。
#include <iostream>
#include <map>
#include <string>
int main() {
const std::string words[] = {"pear", "apple", "apple"};
std::map<std::string, int> counts;
for (const auto& word : words) ++counts[word];
for (const auto& item : counts) {
std::cout << item.first << ' ' << item.second << '\n';
}
}
根据目的选择接口 #
| 目的 | 接口 | 键缺失时 |
|---|---|---|
| 查询是否已有某键 | find(key) |
返回 end() |
| 读取应当存在的值 | at(key) |
抛出 std::out_of_range |
| 获取或建立默认值 | operator[] |
插入新项 |
迭代器访问的 first 是常量键,second 是映射值。改变键的排序位置通常需要删除旧项再插入新项。若只想读取,使用 find 可以防止查询意外改变容器大小。若只关心平均查找速度、不需要按键排序,可改用 std::unordered_map。