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?
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.
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.
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() .
Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once.
A a[2];
for(auto& x_:a){
auto* x = &x_;
// code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With