#include <iostream>
int main (int argc, char** argv)
{
int array[2][3] = {0,1,2,3,4,5};
/**********多维数组遍历方法一**********/
size_t index0 = 0, index1 = 0;
while (index0 < std::size(array))
{
index0++;
while (index1 < std::size(array[index0]))
{
index1++;
std::cout << array[index0][index1] << std::endl;
}
}
/**********多维数组遍历方法二**********/
auto* ptr0_begin = std::begin(array);
auto* ptr0_end = std::end(array);
while (ptr0_begin != ptr0_end)
{
auto* ptr1_begin = std::begin(*ptr0_begin);
auto* ptr1_end = std::end(*ptr0_begin);
while (ptr1_begin != ptr1_end)
{
std::cout << *ptr1_begin << std::endl;
ptr1_begin++;
}
ptr0_begin++;
}
/**********多维数组遍历方法三**********/
for (auto& q : array)
{
for (auto r : q)
{
std::cout << r << std::endl;
}
}
return 0;
}
重点强调:
1、第一方法中std::size()为元函数,为C++17新增;
2、第二种使用指针方法进行遍历;
3、第三种方法中引用的方法进行遍历,可通过C++Insights帮助理解,代码如下:
#include <iostream>
int main()
{
int array[2][3] = {{0, 1, 2}, {3, 4, 5}};
{
int (&__range1)[2][3] = array;
for(int (*__begin1)[3] = __range1, *__end1 = __range1 + 2L; __begin1 != __end1; ++__begin1) {
int (&q)[3] = *__begin1;
{
int (&__range2)[3] = q;
for(int * __begin2 = __range2, *__end2 = __range2 + 3L; __begin2 != __end2; ++__begin2) {
int r = *__begin2;
std::cout.operator<<(r).operator<<(std::endl);
}
}
}
}
}
|