Claude 3.5与Gemini 3.1 Pro图像视频生成深度对比测评
2026/7/3 10:22:28
C++ 中的std::map是 STL(标准模板库)中关联式容器的核心组件,基于红黑树实现,以「键 - 值(key-value)」对的形式存储数据,且会自动按照键的升序排序,是处理有序键值对场景的首选工具。
[]直接按索引访问,仅能按 key 访问)。使用 map 需包含头文件<map>,基础初始化方式:
cpp
运行
#include <iostream> #include <map> #include <string> using namespace std; int main() { // 方式1:空map,key为int,value为string map<int, string> m1; // 方式2:初始化时插入元素 map<int, string> m2 = {{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}}; // 方式3:自定义排序(降序) map<int, string, greater<int>> m3 = {{1, "A"}, {2, "B"}}; // 按key降序:2→1 return 0; }cpp
运行
map<int, string> m; // 方式1:[] 运算符(若key不存在则插入,存在则修改value) m[1] = "Apple"; m[2] = "Banana"; // 方式2:insert() (推荐,避免不必要的默认构造) m.insert(pair<int, string>(3, "Cherry")); m.insert(make_pair(4, "Date")); m.insert({5, "Elderberry"}); // 方式3:emplace() (直接构造,效率更高) m.emplace(6, "Fig");cpp
运行
// 方式1:find() (返回迭代器,未找到则返回 end()) auto it = m.find(3); if (it != m.end()) { cout << "找到:" << it->first << " → " << it->second << endl; } else { cout << "未找到key=3" << endl; } // 方式2:count() (判断key是否存在,返回0或1) if (m.count(4)) { cout << "key=4 存在" << endl; }cpp
运行
// 方式1:按key删除 m.erase(2); // 删除key=2的元素 // 方式2:按迭代器删除 auto it = m.find(5); if (it != m.end()) { m.erase(it); } // 方式3:删除所有元素 m.clear();cpp
运行
map<int, string> m = {{1, "A"}, {2, "B"}, {3, "C"}}; // 方式1:普通迭代器 for (auto it = m.begin(); it != m.end(); ++it) { cout << it->first << " → " << it->second << endl; } // 方式2:范围for(C++11+) for (auto& pair : m) { cout << pair.first << " → " << pair.second << endl; }map的[]运算符若访问不存在的 key,会自动插入该 key,value 为默认构造值(如 string 为空串、int 为 0),需避免误操作。unordered_map(哈希表实现,平均查找效率 O (1)),性能更优。<)或自定义比较函数,否则无法排序。| 特性 | std::map | std::unordered_map |
|---|---|---|
| 底层实现 | 红黑树 | 哈希表 |
| 有序性 | 按 key 升序(可自定义) | 无序 |
| 查找效率 | O(log n) | 平均 O (1),最坏 O (n) |
| 插入 / 删除 | O(log n) | 平均 O (1),最坏 O (n) |
| 内存占用 | 较低(红黑树节点) | 较高(哈希表扩容预留) |
| 适用场景 | 需有序、频繁遍历 | 无需有序、高频查找 |