2

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.

3
  • 2
    for (auto item : list) { => for (auto& item : list) { Commented Apr 19, 2022 at 17:40
  • 1
    auto does not deduce references, so item is a copy of the element. Change to auto& item... Commented Apr 19, 2022 at 17:40
  • Understood. Thanks everyone :) Commented Apr 19, 2022 at 17:44

2 Answers 2

4

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) {
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.