Harold Serrano

View Original

A cooler way to do For-loops in C++

I have to be honest, I have become tired of writing a for-loop as follows:

for(int i=0;i<myVector.size();i++){
//....
}

Luckily, C++ 11 offers a cooler and nicer way to do a for-loop. Now you can do the following as a for loop:

vector<int> myVector{0,1,2,3,4,5}; 
for(auto i:myVector){
    int n=i+2;
}

This new type of for-loop behaves exactly as the one you are accustomed of using. The auto specifier will determine the correct type for the container you are using. The iterator will traverse through each element in the container and assign the value to the "i" variable.

I really like it, especially since I can also pass a reference to it. For example:

vector<MyClass> object{....};

for(auto& n:object){
     n.isCool=true;
}

Since I'm passing the object by reference "&", the above for-loop will modify the value of n.

I have used this new syntax for the for-loop and honestly I feel it is more efficient.

Give it a try.