1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. On an empty std::vector<int> v, what do v.reserve(100) and…

Added 30 Nov -0001

On an empty std::vector&lt;int&gt; v, what do v.reserve(100) and v.resize(100) each produce?

  1. Both set only capacity, differing solely in the exception guarantees offered when a reallocation fails
  2. reserve sets capacity to 100 with size still 0; resize sets size and capacity to 100 with value-initialised elements Correct answer
  3. Both set size to 100, but reserve leaves the new elements uninitialised until each element is written
  4. reserve sets size to 100 and resize only sets capacity, so writing v[0] directly after reserve is perfectly well defined

Correct answer

B. reserve sets capacity to 100 with size still 0; resize sets size and capacity to 100 with value-initialised elements

11 views

MCQSEXAM

Explanation

Capacity versus size: reserve only reallocates the buffer so later growth up to 100 avoids reallocation, leaving size() at 0, so writing v[0] afterwards is undefined behaviour. resize actually creates 100 elements, value-initialising them to 0 for int. Use reserve followed by push_back, or resize followed by indexing, but never mix the two assumptions.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs