Assuming standard headers and using namespace std, what does this C++ code print? vector<int> v = {1, 2, 3}; for (int x : v) x *= 2; for (int& y : v) y += 1; cout << v << v << v;
Correct answer D. 234
Explanation
In the first range-for loop x is a copy of each element, so doubling it has no effect on the vector. The second loop declares y as int&, a reference to each element, so adding 1 updates the vector to 2, 3, 4. Use a reference (or auto&) in range-for whenever you intend to modify the elements.
Answer checked How we write and check questions
Discussion