I can easily simulate a for .. in
loop using initializer lists for read access
std::list<int> foo, bar, baz;
int main()
{
foo.push_back(3);
foo.push_back(2);
bar.push_back(1);
for (auto &x : {foo, bar, baz}) {
// x.push_back(42);
std::cout << x.size() << std::endl;
}
return 0;
}
This prints:
2
1
0
What should I do so that I can modify the actual objects, just as in the commented line:
// x.push_back(42);
A pointer-based trick that we know from C might be applied as follows
for (auto x : { &foo, &bar, &baz }) {
x->push_back(42);
std::cout << x->size() << std::endl;
}
However, this assumes that you actually want to work with the original objects, as opposed to their copies. (The code you posted originally actually works with copies.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With