Yes. auto is preferred. Because if you change the declaration of v to:
std::vector<int> v;
:
std::vector<float> v;
If you use int & in for , you also need to change this. But with auto no need to change!
In my opinion, working with auto more or less like programming on an interface . Therefore, if you perform the += operation in a loop, and you do not need the type of the loop variable e , as long as the type supports the += operation, then auto is the solution:
for(auto & e : v) { e += 2; }
In this example, you don't care that type e supports += with int on the right side. It will work even for custom types that defined operator+=(int) or operator+=(T) , where T is a type that supports implicit conversion from int . It is as if you were programming an interface:
std::vector<Animal*> animals; animals.push_back(new Dog()); animals.push_back(new Cat()); animals.push_back(new Horse()); for(size_t i = 0 ; i < animals.size(); ++i) { animals[i]->eat(food);
Of course you would like to write this loop as:
for(Animal * animal : animals) { animal->eat(food);
Or just this:
for(auto animal : animals) { animal->eat(food);
He is still programming for the interface .
But at the same time, itβs worth noting the comment in the @David comment.
Nawaz
source share