Practice mode C++

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.