循环遍历多维数组

Loop through a multidimensional array?

本文关键字:数组 遍历 循环      更新时间:2023-10-16

我将如何循环通过一个多维数组?假设我们有这样的东西:

class blah
{
    public:
    blah();
    bool foo;
};
blah::blah()
{
    foo = true;
}
blah testArray[1][2];
testArray[1][0].foo = false;

我如何循环testArray来找出foo中哪个是假的呢?

这个不依赖于幻数:

#include <cstddef>
for (size_t x = 0; x < sizeof(*testArray) / sizeof(**testArray); ++x)
for (size_t y = 0; y < sizeof(testArray)  / sizeof(*testArray);  ++y) {
  if (testArray[x][y].foo == false) {
  }
}

x放在外循环中可以获得更好的缓存

class blah
{
    public:
    blah();
    bool foo;
};
blah::blah()
{
    foo = true;
}
int testArrayFirstLength = 1;
int testArraySecondLength = 2;
blah testArray[testArrayFirstLength][testArraySecondLength];
testArray[1][0].foo = false;

for (int i = 0; i < testArrayFirstLength; i++) {
    for (int j = 0; j < testArraySecondLength; j++) {
        if (!testArray[i][j]) {
            blah thing = testArray[i][j]
        }
    }
}

,好吗?还是你在找别的东西?

int x = 0;
int y = 0;
for( x = 0; x < 1; x++ ){
    for( y = 0; y < 2; y++ ){
       if( testArray[x][y].foo == false ){
           //yeah!
       }
    }
}
for (std::size_t i(0); i != 1; ++i){
    for (std::size_t j(0); j != 2; ++j) {
        if (!testArray[i][j].foo) {
            //testArray[i][j].foo is false
            //Perform the required operation
        }
    }
}

在c++ 14中测试(使用指针,因此是安全的)

#include <iostream>
int main()
{
int array[2][2][2]; 
int* pointer=&array[0][0][0]; 
for(int i=0; i<2*2*2; i++)
    {
        std::cout<<*pointer<<std::endl;     
        pointer++; 
    }
}