首页 > 后端开发 > C++ > 正文

c++中如何遍历map的所有键值对_c++遍历map容器中键值对的详细方法

穿越時空
发布: 2025-10-21 08:08:01
原创
743人浏览过
最推荐使用C++17结构化绑定遍历map,语义清晰高效;其次为范围-for循环配合const auto&避免拷贝;传统迭代器适用于老标准,注意使用const_iterator保证只读安全。

c++中如何遍历map的所有键值对_c++遍历map容器中键值对的详细方法

在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++免费学习笔记(深入)”;

使用迭代器(传统方式)

适用于所有 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 简化声明:

速创猫AI简历
速创猫AI简历

一键生成高质量简历

速创猫AI简历 149
查看详情 速创猫AI简历
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。注意避免值拷贝,尤其是键或值较大的时候。

以上就是c++++中如何遍历map的所有键值对_c++遍历map容器中键值对的详细方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号