c++ map怎么遍历 c++ map遍历方法总结

admin 百科 20
C++中遍历map的常用方法包括:1. 范围for循环(C++11),简洁高效,推荐使用const auto&避免拷贝;2. 传统迭代器,兼容性好,可选用const_iterator保证只读;3. auto简化迭代器声明,代码更清晰;4. std::for_each配合lambda,适合函数式编程场景;5. 反向遍历使用reverse_iterator从大到小访问键。遍历时应避免修改容器,优先使用引用防止拷贝,且map遍历顺序默认按键升序排列。

c++ map怎么遍历 c++ map遍历方法总结-第1张图片-佛山资讯网

在C++中,map 是一个关联容器,用于存储键值对(key-value pairs),并且按键有序排列。遍历 map 是日常开发中的常见操作。以下是几种常用的 C++ map 遍历方法总结。

1. 使用范围 for 循环(C++11 及以上)

这是最简洁、推荐的方式,适用于现代 C++ 项目。

#include <map>
#include <iostream>

std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};

for (const auto&amp;amp;amp; pair : myMap) {
    std::cout << pair.first << ": " << pair.second << std::endl;
}

登录后复制

说明: auto&const auto&amp;amp; 可避免拷贝,提高效率。适合只读访问。

2. 使用迭代器(传统方式)

适用于所有 C++ 标准版本,兼容性好。

立即学习“C++免费学习笔记(深入)”;

for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
}

登录后复制

如果不需要修改元素,建议使用 const_iterator:

for (std::map<int, std::string>::const_iterator it = myMap.cbegin(); it != myMap.cend(); ++it) {
    std::cout << it->first << ": " << it->second << std::endl;
}

登录后复制

3. 使用 auto 简化迭代器声明(C++11 起)

结合 auto 和迭代器,代码更简洁。

标签: go 编码 ai c++ ios stream 键值对 排列

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~