C++11 range based auto for loop by value, reference, and pointer

偶尔善良 提交于 2019-12-03 13:28:43
A a[2];
for(auto& x_:a){
  auto* x = &x_;
  // code
}

You don't. If you want a pointer, either write a classical for-loop, or loop by reference and take the address.

I'm not recommending it, but if you insist on using pointer -> syntax, just make an array of A* and treat it like a value (i.e. do regular auto in the range-for loop)

#include <iostream>

struct A {
 void fun() { std::cout << "fun \n"; };
};

int main() {
  A* a[2];

  // Pointer
  for (auto x : a) {
    x->fun();
  }
}

Live Example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!