map是C++ STL中基于红黑树的关联容器,用于存储唯一键值对并自动排序,插入、删除、查找时间复杂度为O(log n);需包含头文件<map>,定义语法为std::map<KeyType, ValueType> name;可通过insert、下标[]或emplace插入元素,推荐emplace更高效;访问可用[]或at(),后者在键不存在时抛出异常更安全;遍历支持范围for循环或迭代器;查找用find()或count(),删除用erase();注意避免对只读操作使用[]以防意外插入默认值。

在C++中,map 是一个非常实用的关联容器,属于标准模板库(STL)的一部分。它用于存储键值对(key-value pairs),其中每个键都是唯一的,并且自动按照键的顺序排序。map 的底层通常由红黑树实现,因此插入、删除和查找操作的时间复杂度为 O(log n)。
要使用 map,需要包含对应的头文件:
#include <map>
定义一个 map 的基本语法如下:
std::map<KeyType, ValueType> mapName;
例如,创建一个以字符串为键、整数为值的 map:
立即学习“C++免费学习笔记(深入)”;
std::map<std::string, int> studentScores;
向 map 中添加键值对有多种方法:
studentScores.insert({"Alice", 85});studentScores["Bob"] = 90;
注意:如果键已存在,[] 会覆盖原值;若不存在,则创建新元素。
studentScores.emplace("Charlie", 78);可以通过键直接访问值(使用 [] 或 at()):
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关联容器使用指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号