简体   繁体   English

循环通过多维数组?

[英]Loop through a multidimensional array?

How would I loop through a multidimensional array? 我如何循环遍历多维数组? Say we had something like this: 说我们有这样的事情:

class blah
{
    public:
    blah();
    bool foo;
};

blah::blah()
{
    foo = true;
}

blah testArray[1][2];
testArray[1][0].foo = false;

How would I go about looping through testArray to find which one of foo is false? 我将如何循环通过testArray来查找哪个foo是假的?

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

That good? 那么好? Or were you looking for something else? 或者你在寻找别的东西?

This one isn't dependent on magic numbers: 这个不依赖于幻数:

#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) {

  }
}

Having x in the outer loop leads to better caching. 在外循环中使用x可以获得更好的缓存。

Tested in c++ +14 (using pointers, so be safe) 在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++; 
    }
}
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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM