3-5&&6 Array

遍历二维数组的三种方式

#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;
}
上一篇:Html5游戏开发攻略(Canvas设置篇)


下一篇:Cow relays