map是C++中用于存储唯一键值对并自动排序的关联容器,定义在<map>头文件中,支持insert、下标等方式插入,可使用范围for或迭代器遍历,推荐用find查找以避免下标访问导致的意外插入。

在C++中,map 是一种关联容器,用于存储键值对(key-value pairs),其中每个键都唯一,并自动按照键的顺序排序。它定义在 <map> 头文件中,通常用于需要快速查找、插入和删除数据的场景。
包含头文件并声明 map
使用 map 前需要包含对应的头文件,并通过模板参数指定键和值的类型:
#include <iostream>#include <map>
#include <string>
using namespace std;
声明一个 map,例如存储学号(int)与姓名(string)的映射:
map<int, string> studentMap;插入键值对的几种方式
有多种方法可以向 map 中添加元素:
立即学习“C++免费学习笔记(深入)”;
-
使用 insert() 方法:
studentMap.insert({101, "Alice"});
studentMap.insert(make_pair(102, "Bob")); -
使用下标操作符 []:
studentMap[103] = "Charlie";
注意:如果键已存在,[] 会覆盖原值;若不存在,则创建新元素。
遍历 map 中的键值对
可以使用范围 for 循环配合结构化绑定(C++17 起支持)来遍历:
for (const auto& [id, name] : studentMap) {cout << "ID: " << id << ", Name: " << name << endl;
}
如果不支持 C++17,可使用迭代器:
for (auto it = studentMap.begin(); it != studentMap.end(); ++it) {cout << "ID: " << it->first << ", Name: " << it->second << endl;
}
查找和访问元素
使用 find() 可判断键是否存在:
auto it = studentMap.find(102);if (it != studentMap.end()) {
cout << "Found: " << it->second << endl;
} else {
cout << "Not found!" << endl;
}
也可以直接用 [] 访问,但注意:如果键不存在,[] 会自动插入一个默认值,可能造成意外结果。
完整示例代码
#include <iostream>#include <map>
#include <string>
using namespace std;
int main() {
map<int, string> students;
students.insert({101, "Alice"});
students[102] = "Bob";
students.insert(make_pair(103, "Charlie"));
for (const auto& [id, name] : students) {
cout << "ID: " << id << ", Name: " << name << endl;
}
return 0;
}
输出结果:
ID: 101, Name: AliceID: 102, Name: Bob
ID: 103, Name: Charlie
基本上就这些。map 自动排序、键唯一、操作高效,是处理键值映射的常用选择。注意根据需求选择插入和访问方式,避免无意中创建多余元素。










