C++遍历二维数组的四种方法

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::begin;
using std::end;
int main()
{
int ia[3][4];
size_t cnt=0;
for (auto &row:ia){
    for (auto &col:row){
        col=cnt;
        ++cnt;
    }
}

constexpr size_t rowCnt=3,colCnt=4;
for (size_t i=0;i != rowCnt; ++i){
    for (size_t j=0;j != colCnt;++j){
        cout << ia[i][j] <<endl;
    }
}
for (int(*p)[4] = ia;p != ia+3;p++){
    for (int *q = *p;q != *p+4;q++){
        cout << *q << endl;
    }
}
for (int(*p)[4] = begin(ia);p != end(ia);p++){
    for (int *q = begin(*p);q != end(*p); q++){
        cout << *q <<endl;
    }
}
for (int (&p)[4]:ia){
    for (int &q:p){
        cout << q << endl;
    }
}
return 0;
}

 

posted @ 2017-03-01 21:39  ywliao  阅读(8129)  评论(0编辑  收藏  举报