Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 700
ckain Avatar asked Nov 27 '13 10:11

ckain


People also ask

Are there range based for loops in C?

Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Is Auto a pointer in C++?

The C++ standard provides class template auto_ptr in header file <memory> to deal with this situation. Our auto_ptr is a pointer that serves as owner of the object to which it refers. So, an object gets destroyed automatically when its auto_ptr gets destroyed.

Why we use range based for loop?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .

Are range based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once.


1 Answers

A a[2];
for(auto& x_:a){
  auto* x = &x_;
  // code
}
like image 141
Yakk - Adam Nevraumont Avatar answered Oct 27 '22 00:10

Yakk - Adam Nevraumont