Home > Software engineering >  Range Based For Loop on std::array
Range Based For Loop on std::array

Time:04-20

I have an array of arrays and want to fill them up with some value.

This doesn't work:

std::array<std::array<int, 5>, 4> list;

for (auto item : list) {
    std::fill(item.begin(), item.end(), 65);
}

However, this does:

for (int i = 0; i < 4; i  ) {
    std::fill(list[i].begin(), list[i].end(), 65);
}

What am I missing? Looking at the debugger, the first example does nothing on list. The type of item is std::array<int, 5>, as expected, so I'm not sure what went wrong.

CodePudding user response:

Your first loop is roughly equivalent to:

for (int i = 0; i < 4; i  ) {
    auto item = list[i];
    std::fill(item.begin(), item.end(), 65);
}

Can you spot the problem? item is a copy of the array element. You are modifying the copy and not the element. Simple solution: Use a reference:

for (auto& item : list) {

CodePudding user response:

In your first code snippet, the item variable will be a copy of each array in the loop; so, modifying that will not affect the 'originals'. In fact, as that item is never actually used, the whole loop may be "optimized away" by the compiler.

To fix this, make item a reference to the iterated array elements:

for (auto& item : list) {
    //...
  • Related