3-5&&6 C++数组遍历

遍历二维数组的三种方式

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
    //初始化二维数组
    int map[3][4] = {};
    for(int cow = 0; cow < 3; cow++)
        for(int col = 0; col < 4; col++)
            map[cow][col] = cow+col;
	
    //第一种方法:范围for【外层for必须要用引用,否则cow会被转换为指针,而指针不支持内层的范围f】
    cout<<"the first version : use range for"<<endl;
    for(int (&cow)[4] : map){
        for(int col : cow)
            cout<<col<<" ";
        cout<<endl;
    }
    cout<<endl;

    //第二种方法:下标
    cout<<"the second version : use for loop by subscript"<<endl;
    for(int cow = 0; cow < 3; cow++){
        for(int col = 0; col < 4; col++)
            cout<<map[cow][col]<<" ";
        cout<<endl;
    }
    cout<<endl;

    //第三种方法:指针【不用auto】
    cout<<"the third version : ues for loop by pointers"<<endl;
    for(int (*p)[4] = map; p < map+3; p++){
        for(int *q = *p; q < *p+4; q++)
            cout<<*q<<" ";
        cout<<endl;
    }
    cout<<endl;

     //第三种方法:指针【用auto】
    cout<<"we can also write it like this"<<endl;
    for(auto p = begin(map); p != end(map); p++){
        for(auto q = begin(*p); q != end(*p); q++)
            cout<<*q<<" ";
        cout<<endl;
    }
    cout<<endl;
}
posted @   咪啪魔女  阅读(408)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示