Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a multidimensional array?

Tags:

c++

arrays

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?

like image 998
Lemmons Avatar asked Mar 07 '26 12:03

Lemmons


2 Answers

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.

like image 86
Pubby Avatar answered Mar 10 '26 02:03

Pubby


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?

like image 29
DanZimm Avatar answered Mar 10 '26 00:03

DanZimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!