ckain
ckain

Reputation: 423

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

I know how to use auto keyword in for loop to iterate this array either by value or reference.

struct A {
 void fun() {};
};

int main() {
  A a[2];

  // Value
  for (auto x : a) {
    x.fun();
  }

  // Ref
  for (auto& x : a) {
    x.fun();
  }

  // Pointer
  //for (...) {
    x->fun();
  }
}

So I am looking third version of this convention. How do I use pointer here?

Upvotes: 10

Views: 6143

Answers (3)

TemplateRex
TemplateRex

Reputation: 70516

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

Upvotes: 3

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275270

A a[2];
for(auto& x_:a){
  auto* x = &x_;
  // code
}

Upvotes: 12

Sebastian Redl
Sebastian Redl

Reputation: 71899

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

Upvotes: 7

Related Questions