如何使用初始化列表循环来修改元素?

mar*_*trz 12 c++ initializer-list

我可以for .. in使用初始化程序列表轻松模拟循环以进行读取访问

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;
}
Run Code Online (Sandbox Code Playgroud)

这打印:

2
1
0
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能修改实际对象,就像在注释行中一样:

// x.push_back(42);
Run Code Online (Sandbox Code Playgroud)

AnT*_*AnT 20

我们从C中知道的基于指针的技巧可能如下应用

  for (auto x : { &foo, &bar, &baz }) {
    x->push_back(42);
    std::cout << x->size() << std::endl;
  }
Run Code Online (Sandbox Code Playgroud)

但是,这假设您实际上想要使用原始对象,而不是它们的副本.(您最初发布的代码实际上适用于副本.)


Chr*_*rew 17

你可以使用std::reference_wrapper:

for (std::list<int>& x : {std::ref(foo), std::ref(bar), std::ref(baz)}) {
  x.push_back(42);
  std::cout << x.size() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)