Tony Zhang
Tony Zhang

Reputation: 33

Range Based For Loop on std::array

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.

Upvotes: 2

Views: 1523

Answers (2)

eerorika
eerorika

Reputation: 238341

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

Upvotes: 4

Adrian Mole
Adrian Mole

Reputation: 51825

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

Upvotes: 2

Related Questions