10

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?

1
  • 7
    A pointer is a value type. Commented Nov 27, 2013 at 10:18

3 Answers 3

12
A a[2]; for(auto& x_:a){ auto* x = &x_; // code } 
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

3

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

2 Comments

Ew, no, don't... and Xeo never said to do this.
@LightnessRacesinOrbit I agree on the ew, but just wanted to point it out in case the OP insists on using -> syntax. Updated the answer, tnx.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.