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

c++map遍历

作者:铁打的心,也会穿孔,   发布日期:2026-07-21   浏览:71

#include <iostream>
#include <map>

int main() {
    // 创建一个map,键为整数,值为字符串
    std::map<int, std::string> myMap;

    // 向map中插入一些元素
    myMap[1] = "one";
    myMap[2] = "two";
    myMap[3] = "three";

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

    // 方法2: 使用范围for循环(C++11及以上版本)
    std::cout << "\n方法2: 使用范围for循环遍历map" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // 方法3: 使用基于范围的for循环和结构化绑定(C++17及以上版本)
    std::cout << "\n方法3: 使用基于范围的for循环和结构化绑定遍历map" << std::endl;
    for (const auto& [key, value] : myMap) {
        std::cout << "Key: " << key << ", Value: " << value << std::endl;
    }

    return 0;
}

解释说明:

  1. 创建和初始化map:我们创建了一个std::map<int, std::string>类型的map,并向其中插入了一些键值对。
  2. 方法1:使用迭代器遍历map:通过std::map::iterator来遍历map中的每个元素,访问键和值。
  3. 方法2:使用范围for循环(C++11及以上版本):使用范围for循环简化遍历过程,直接遍历map中的每个键值对。
  4. 方法3:使用基于范围的for循环和结构化绑定(C++17及以上版本):进一步简化代码,使用结构化绑定将键和值解包到变量中。

上一篇:c++ set用法

下一篇:c++ sin

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

嵌入式c++

c++框架代码

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

Laravel 中文站