2011-11-13 12 views
1

多次元配列をループする方法は?私たちはこのような何かを持っていたと言う:多次元配列をループする?

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

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

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

どのように私はfooの一つが偽である見つけるためにtestArrayをループに行きますか?

+1

任意の他の配列を介して、あなたのループと同じように、ループの本体は別のループ – Robert

+1

'testArray [1]になり除い[0 ] 'が宣言された配列の範囲外です –

+0

擬似コードです。関係ない。擬似コードで飛ぶことさえできます。 – Lemmons

答えて

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

いいですか?あなたは何か他のものを探していましたか?

+0

うん、それは動作します。ありがとう! – Lemmons

0
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! 
     } 
    } 
} 
0
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 
     } 
    } 
} 
4

この1つのマジックナンバーに依存しない:

より良いキャッシュに外側のループのリードで xを持つ
#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) { 

    } 
} 

。 (それほど安全で、ポインタを用いて)+14 C++でテストさ

+1

+1 ...だが、 '#include 'と 'std :: size_t'を使うといいだろうか?それは私のペットピーブです。行がすべて同じ長さではない場合はどうでしょうか? –

+0

@ keith.layneヘッダーを追加しますが、 'std'は必要ありません。異なる行で配列型を定義することはできますか? – Pubby

+0

グローバルな名前空間で宣言されたのを知らなかったので、今は気が気になりません。私はあなたの質問をチェックしています。 –

0

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