Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use initializer-list loops for modifying elements?

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);
like image 553
marmistrz Avatar asked Jun 06 '17 13:06

marmistrz


1 Answers

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

like image 147
AnT Avatar answered Oct 11 '22 13:10

AnT