0
What is the function of auto and &(x) ? (they work the same way in this snippet of code below)
vector<int> v{3,1,4,1,5,9}; for(int &x: v) cout<< x << ' ' ; cout<< '\n'; for(auto x: v) cout<< x << ' ';
1 Answer
+ 8
The "auto" keyword was introduced in C++11 so that you don't have to write
std::vector<std::pair<std::vector<int>, int>>
and other lengthy types every time you need to iterate over it, or to declare one with initialization.
The compiler would deduce what datatype the variable/object should be. There are limitations though:
auto x = 5; // ok
auto x; // error
x = 5;
As for &, it's used to tell the compiler that x is a reference of the original elements in v, not merely a temporary variable storing the values of elements in v. Altering x will alter the elements in v.