簡體   English   中英

循環通過多維數組?

[英]Loop through a multidimensional array?

我如何循環遍歷多維數組? 說我們有這樣的事情:

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

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

blah testArray[1][2];
testArray[1][0].foo = 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]
        }
    }
}

那么好? 或者你在尋找別的東西?

這個不依賴於幻數:

#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可以獲得更好的緩存。

在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