Change list item

Sorry for my English.

Some classes:

class Kid {
public:
    ...
    string _name;
    std::list<string> _cuteKids;
};

      

Use class:

    std::list<Kid> kids;
    kids.push_back(new Kid("Jeck"));
    kids.push_back(new Kid("Anna"));
    kids.push_back(new Kid("Toma"));

    for(auto e: kids) {

         e._cuteKids.push_back("Jeck"); // Many some names...
         [1]
    }
    [2]

      

If you look at the code in the debugger, the list at point 1 _cuteKids - has an element. But if you look at the list in paragraph 2 of _cuteKids - there is no item. Why?

This is just an example, I'm actually a very complex algorithm, but the bottom line is that after the loop, _cuteKids becomes empty. It's like it's a static variable (e: kids) and not a pointer to kids variable .

+3


source to share


2 answers


In your code:

for (auto e: kids) {
    e._cuteKids.push_back("Jeck"); // Many some names...
}

      

you make copies of every item in the container kids

, iterate over the container itself because you missed the "simple" .. p> &

So the operator e._cuteKids.push_back(...);

works with a copy not in the original element. This local copy "evaporates" after each iteration of the loop, and the original items in the container are kids

not affected.

You have to iterate over correctly using ( ) references&

to the original elements to avoid those local deep copies:

for (auto& e : kids) {
    // ... do something on 'e' ...
}

      




Note that there is a suggestion for too> t loop> tots> (N3994) that could be part of the next iteration of the language (C ++ 17?) To avoid errors like those from the code:

Range-based loops: the next generation (version 1)

Using this new syntax, one can simply write:

for (e : kids) {
    // ... do something on 'e' ...
}

      

without introducing subtle mistakes like forgetting &

.

+1


source


e

is a copy of the list items, so changes to it do not affect the items in the list.

To do what you want, make a e

link:



for (auto &e : kids)

      

+4


source







All Articles