先看一个一维数组的简洁遍历方式:
int a[6] ={8,2,1,3,4,5}; for(auto &e:a) cout<<e<<" ";
再看二维数组的遍历常用方式:
int ia[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; //1 for (auto &row:ia){ for (auto &col:row){ cout << col <<endl; } } //2 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; } } //3 for (int(*p)[4] = ia;p != ia+3;p++){ for (int *q = *p;q != *p+4;q++){ cout << *q << endl; } } //4 (与3基本相同) for (int(*p)[4] = begin(ia);p != end(ia);p++){ for (int *q = begin(*p);q != end(*p); q++){ cout << *q <<endl; } } //5 (注意与1的区别) for (int (&p)[4]:ia){ for (int &q:p){ cout << q << endl; } }
来源:51CTO
作者:Zachary Yu
链接:https://blog.csdn.net/qq_43145072/article/details/100830817