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.
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) {
//...