范围基于多维阵列上 [英] range-based for on multi-dimensional array

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

问题描述

我的嵌入式系统得到了g ++的一个C ++ 11功能的版本,所以我一直在从

清理code

 为(uint16_t * P =阵列; P<(安培;数组)[1]; ++ P){
    * P = fill_value;
}

 为(uint16_t&安培; R:数组){
    R = fill_value;
}

这是的可读性更强。

有一个范围为基础的环路工作在数组2中的所有元素[M] [N]

旧的版本是

 为(int16_t * P =数组2 [0]; P<(安培;数组2)[1] [0]; +​​+ P){
    * P = fill_value;
}

和我不希望嵌套的循环,除非它保证了编译器将压平他们。

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


解决方案

 为(自动和放大器;一个:数组)
{
   为(中间体&放大器; X:一)X = fill_value;
}

编辑:您可以尝试以下

 常量为size_t N = 2;
常量为size_t M = 3;诠释一个[n]的[米] = {{1,2,3},{4,5,6}};为(自动&放大器; X:reinter pret_cast&下; INT(安培;)[n * m个]≥(一))×= 10;
为(自动X:reinter pret_cast&下; INT(安培;)[n * m个]≥(一))的std ::法院&所述;&下;点¯x所述&;&下; '';
性病::法院LT&;<的std :: ENDL ;;

的输出是

  10 10 10 10 10 10

这种方法的好处是,你可以reinter preT任何多维数组不仅是一个二维数组。例如:

  int类型的[N] [M] [K] = {/ *一些初始化* /};为(自动X:reinter pret_cast&下; INT(安培;)[sizeof的(A)/的sizeof(***一个)]≥(a))的
{
    性病::法院LT&;<点¯x所述&;&下; '';
}
性病::法院LT&;<的std :: ENDL ;;

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;
}

to

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

which is much more readable.

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

The old version is

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, the compiler is the GNU 4.7.4 Linaro g++ ARM cross-compiler that ships with TI Code Composer Studio 6.0.0)

解决方案

for ( auto &a : array )
{
   for ( int &x : a ) x = fill_value;
}

EDIT: You can try the following

const size_t n = 2;
const size_t m = 3;

int a[n][m] = { { 1, 2, 3 }, { 4, 5, 6 } };

for ( auto &x : reinterpret_cast<int ( & )[n * m]>( a ) )  x = 10;
for ( auto x : reinterpret_cast<int ( & )[n * m]>( a ) )  std::cout << x << ' ';
std::cout << std::endl;;

The output is

10 10 10 10 10 10 

The advantage of this approach is that you can reinterpret any multidimensional array not only a two-dimensional array. For example

int a[n][m][k] = { /* some initializers */ };

for ( auto x : reinterpret_cast<int ( & )[sizeof( a ) / sizeof( ***a )]>( a ) )
{
    std::cout << x << ' ';
}
std::cout << std::endl;;

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

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