The book i am reading offers this example when iterating over a vector
for (auto &e: v) {
cout << e << endl;
}
Suppose v is declared as vector<int> v, in other words, we know that the type of elements inside this collection is int.
Is using auto in any way better or preferred to?
for (int &e: v) {
cout << e << endl;
}
Why?
Yes.
autois preferred. Because if you change the declaration ofvfrom:to this:
If you use
int &in thefor, then you have to change that as well. But withauto, no need to change!In my opinion, working with
autois more or less like programming to interface. So if you do an operation+=in the loop, and you don’t really care about the type of the loop variableeas long as the type supports+=operation, thenautois the solution:In this example, all you care about that the type of
esupports+=withinton the right hand side. It will work even for user-defined types, which has definedoperator+=(int), oroperator+=(T)whereTis a type which supports implicit conversion fromint. It is as if you’re programming to interface:Of course, you would like to write this loop as:
Or simply this:
It is still programming to interface.
But at the same time, the point in @David’s comment is worth noting.