
在C++中,map 是一个非常实用的关联容器,属于标准模板库(STL)的一部分。它用于存储键值对(key-value pairs),其中每个键都是唯一的,并且自动按照键的顺序排序。map 的底层通常由红黑树实现,因此插入、删除和查找操作的时间复杂度为 O(log n)。
包含头文件与定义 map要使用 map,需要包含对应的头文件:
#include <map>
定义一个 map 的基本语法如下:
std::map<KeyType, ValueType> mapName;
例如,创建一个以字符串为键、整数为值的 map:
std::map<std::string, int> studentScores;插入元素的几种方式
向 map 中添加键值对有多种方法:
- 使用 insert() 方法:
studentScores.insert({"Alice", 85});
studentScores["Bob"] = 90;
注意:如果键已存在,[] 会覆盖原值;若不存在,则创建新元素。
studentScores.emplace("Charlie", 78);
访问与遍历 map 元素
可以通过键直接访问值(使用 [] 或 at()):
HyperWrite
AI写作助手帮助你创作内容更自信
54
查看详情
int score = studentScores["Alice"]; // 若键不存在,[] 会创建默认值
int score = studentScores.at("Alice"); // 若键不存在,at() 抛出异常
推荐使用 at() 在需要安全访问时防止意外插入。
遍历 map 可使用范围 for 循环:
for (const auto& pair : studentScores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
也可以使用迭代器:
for (auto it = studentScores.begin(); it != studentScores.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
查找与删除元素
使用 find() 查找指定键:
auto it = studentScores.find("Alice");
if (it != studentScores.end()) {
std::cout << "Found: " << it->second;
}
使用 count() 判断键是否存在(返回 0 或 1):
if (studentScores.count("Bob")) {
std::cout << "Bob exists.";
}
删除元素使用 erase():
studentScores.erase("Alice"); // 按键删除
studentScores.erase(it); // 按迭代器删除
基本上就这些。map 使用起来直观高效,适合需要按键快速查找、自动排序的场景。注意避免频繁使用 [] 访问只读数据,以免无意中插入默认值。掌握 insert、find、erase 和遍历方法,就能灵活应对大多数需求。不复杂但容易忽略细节。
以上就是c++++中如何使用map_c++ map关联容器使用指南的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: ai c++ 键值对 count for 字符串 循环 map 大家都在看: c++中怎么使用正则表达式_c++正则表达式库使用方法 c++中printf和cout哪个更快_C++ printf与cout性能对比评测 c++中预处理器指令有哪些_c++常用预处理器指令详解 c++中继承是怎么实现的_C++继承机制与实现 C++结构体拷贝与内存管理解析






发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。