Reputation: 197
To iterate through a C style multidimensional array we have
int arr[3][4];
for (int row = 0; row < 3; row++){
for (int col = 0; col < 4; col++){
...
}
}
But how may one use iterators to iterate over the following:
array<array<int, 4>, 3> arr;
Using the following iterators?
array<array<int, 4>, 3>::iterator it1;
array<int, 4>::iterator it2;
Upvotes: 0
Views: 72
Reputation: 1052
As usual:
array<array<int, 4>, 3> arr;
for(array<array<int, 4>, 3>::iterator it1 = arr.begin(); it1 != arr.end(); ++it1)
for(array<int, 4>::iterator it2 = it1->begin(); it2 != it1->end(); ++it2)
(*it2) = 0;
But it would be easier to use short c++11 range-based for loops
array<array<int, 4>, 3> arr;
for(auto &it1 : arr)
for(auto &it2 : it1)
it2 = 0;
Upvotes: 1
Reputation: 171127
If you need to use iterators, use them as usual:
for (auto itOuter = arr.begin(); itOuter != arr.end(); ++itOuter) {
for (auto itInner = itOuter->begin(); itInner != itOuter->end(); ++itInner) {
// use *itInner as appropriate
}
}
You can just as well use range-based for
loops, if they'd work for you:
for (auto &inner : arr) {
for (int &elem : inner) {
// use elem as appropriate
}
}
Upvotes: 2