最推荐使用C++17结构化绑定遍历map,语义清晰高效;其次为范围-for循环配合const auto&避免拷贝;传统迭代器适用于老标准,注意使用const_iterator保证只读安全。
在C++中,map 是一种关联容器,用于存储键值对(key-value pairs),并且按键有序排列。遍历 map 中的所有键值对是日常编程中的常见操作。以下是几种常用且高效的方法来遍历 map 的键值对。
使用范围-based for 循环(C++11 及以上)
这是最简洁、推荐的方式,适用于现代 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++ 标准版本,兼容性好。
#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;
}
使用 const_iterator 遍历只读数据
当你不需要修改 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 起)
C++17 引入了结构化绑定,让代码更清晰易读。
for (const auto& [key, value] : scores) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
这是目前最推荐的写法,语义清晰,减少出错可能。
基本上就这些方法。根据你的编译器支持选择合适的方式:优先用 C++17 的结构化绑定,其次是范围-for + auto,兼容性要求高则用迭代器。不复杂但容易忽略细节,比如是否加引用、是否用 const。注意避免值拷贝,尤其是键或值较大的时候。
本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。
还木有评论哦,快来抢沙发吧~