Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ map 遍历

作者:幸福的起点   发布日期:2025-12-02   浏览:48

#include <iostream>
#include <map>

int main() {
    // 创建一个map,键为字符串,值为整数
    std::map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};

    // 方法1: 使用基于范围的for循环遍历map
    std::cout << "Method 1: Range-based for loop" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    // 方法2: 使用迭代器遍历map
    std::cout << "\nMethod 2: Iterator" << std::endl;
    for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    // 方法3: 使用C++11的auto关键字和迭代器遍历map
    std::cout << "\nMethod 3: C++11 auto and iterator" << std::endl;
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    // 方法4: 使用C++11的auto关键字和基于范围的for循环遍历map
    std::cout << "\nMethod 4: C++11 auto and range-based for loop" << std::endl;
    for (const auto& [key, value] : myMap) {
        std::cout << key << ": " << value << std::endl;
    }

    return 0;
}

解释说明:

  1. 创建 map:我们创建了一个 std::map,其中键是 std::string 类型,值是 int 类型。
  2. 方法1:基于范围的for循环:这是最简洁的方式,直接遍历 map 中的每个键值对。
  3. 方法2:使用迭代器:通过迭代器从 begin()end() 遍历 map,这种方式在 C++98/03 中常用。
  4. 方法3:使用 C++11 的 auto 关键字和迭代器:简化了代码,减少了类型声明。
  5. 方法4:使用 C++17 的结构化绑定:结合 auto 和基于范围的for循环,进一步简化了代码,直接解构出键和值。

每种方法都能有效地遍历 map,选择哪种方式取决于你的编码风格和 C++ 标准版本。

上一篇:c++获取数组长度

下一篇:https c++ openssl

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

进制转换c++代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站