基于多维数组的范围 [英] range-based for on multi-dimensional array

查看:27
本文介绍了基于多维数组的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的嵌入式系统有一个支持 C++11 的 g++ 版本,所以我一直在清理代码

My embedded system got a C++11-capable version of g++, so I've been cleaning up code from

for( uint16_t* p = array; p < (&array)[1]; ++p ) {
    *p = fill_value;
}

for( uint16_t& r : array ) {
    r = fill_value;
}

更具可读性.

是否有一个基于范围的 for 循环来操作 array2[m][n] 的所有元素?

Is there a range-based for loop which operates over all elements of array2[m][n]?

旧版本是

for( int16_t* p = array2[0]; p < (&array2)[1][0]; ++p ) {
    *p = fill_value;
}

而且我不想要嵌套循环,除非可以保证编译器将它们展平.

and I don't want nested loops, unless it's guaranteed the compiler will flatten them.

(FWIW,编译器是 TI Code Composer Studio 6.0.0 附带的 GNU 4.7.4 Linaro g++ ARM 交叉编译器)

(FWIW, the compiler is the GNU 4.7.4 Linaro g++ ARM cross-compiler that ships with TI Code Composer Studio 6.0.0)

推荐答案

例如,有多种方法可以打印和操作多维数组的值.

As an example, there are various ways to print and manipulate value of a multidimensional array.

int arr[2][3] = { { 2, 3, 4 }, { 5, 6, 7} };  

第一种方法,

size_t count = 0 ; 

for( auto &row : arr)
    for(auto &col : row)
         col = count ++; 

在第一个 for 循环中,我们指的是两个数组.然后在第二个数组中,我们分别引用了这些子数组的 3 个元素.我们还为 col 分配了计数.因此,它迭代到子数组的下一个元素.

Here in the first for loop we are referring to the two array. Then in the second array we have reference to the 3 elements of those subarrays separately. And we are also assigning count to col. So, it iterates over to the next element of the subarray.

第二种方法,

for( auto &row : arr)
     for( auto col : row)
          cout << col << endl; 

我们在第一个循环中引用这里,因为我们想避免数组到指针的转换.

We take reference here in the first loop because we want to avoid array to pointer conversion.

如果这样做了(错误情况:第一个 for 循环不是引用),

If this is done( error case: first for loop is not a reference ),

for( auto row : arr)          // program won't compile
     for( auto col : row)

这里,我们有 int * 行.当我们到达第二个 for 循环时.因为 row 现在是 int * 而不是列表,程序将无法编译.您必须创建一个列表,然后我们才能将其传递给 ranged for 循环并使用它来迭代该列表.

Here, we have int * in row. By the time we reach the second for loop. Because row is now int * and not a list the program will not compile. You have to create a list then only we can pass that it to ranged for loop and use it for iterating over that list.

vector<int> list = { *(row+0) , *(row+1) , *(row+ 2) } ;

现在我们可以使用列表进行迭代

Now we can use the list for iteration

for ( ----- : list)

这篇关于基于多维数组的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆