最推荐使用C++17结构化绑定遍历map,语义清晰高效;其次为范围-for循环配合const auto&避免拷贝;传统迭代器适用于老标准,注意使用const_iterator保证只读安全。

在C++中,map 是一种关联容器,用于存储键值对(key-value pairs),并且按键有序排列。遍历 map 中的所有键值对是日常编程中的常见操作。以下是几种常用且高效的方法来遍历 map 的键值对。
这是最简洁、推荐的方式,适用于现代 C++ 编程。
通过自动推导元素类型,可以直接访问每一对 std::pair<const Key, Value>。
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> scores = {
{"Alice", 90},
{"Bob", 85},
{"Charlie", 95}
};
for (const auto& pair : scores) {
std::cout << "Key: " << pair.first
<< ", Value: " << pair.second << std::endl;
}
return 0;
}
说明:使用 const auto& 避免拷贝,提高效率;pair.first 是键,pair.second 是值。
立即学习“C++免费学习笔记(深入)”;
适用于所有 C++ 标准版本,兼容性好。
#include <map>
#include <iostream>
int main() {
std::map<std::string, int> scores = {
{"Alice", 90},
{"Bob", 85},
{"Charlie", 95}
};
for (std::map<std::string, int>::iterator it = scores.begin();
it != scores.end(); ++it) {
std::cout << "Key: " << it->first
<< ", Value: " << it->second << std::endl;
}
return 0;
}
也可以使用 auto 简化声明:
for (auto it = scores.begin(); it != scores.end(); ++it) {
std::cout << "Key: " << it->first
<< ", Value: " << it->second << std::endl;
}
当你不需要修改 map 内容时,建议使用 const_iterator,保证安全性。
for (std::map<std::string, int>::const_iterator it = scores.cbegin();
it != scores.cend(); ++it) {
std::cout << "Key: " << it->first
<< ", Value: " << it->second << std::endl;
}
或配合 auto 使用:
for (auto it = scores.cbegin(); it != scores.cend(); ++it) {
// 同上
}
C++17 引入了结构化绑定,让代码更清晰易读。
for (const auto& [key, value] : scores) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
这是目前最推荐的写法,语义清晰,减少出错可能。
基本上就这些方法。根据你的编译器支持选择合适的方式:优先用 C++17 的结构化绑定,其次是范围-for + auto,兼容性要求高则用迭代器。不复杂但容易忽略细节,比如是否加引用、是否用 const。注意避免值拷贝,尤其是键或值较大的时候。
以上就是c++++中如何遍历map的所有键值对_c++遍历map容器中键值对的详细方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号