1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. What is the difference between size() and capacity() on a…

Added 30 Nov -0001

What is the difference between size() and capacity() on a C++ std::vector?

  1. Both return the same value after every operation
  2. capacity counts only elements added with push_back
  3. size is elements stored; capacity is allocated slots Correct answer
  4. size is allocated slots; capacity is elements stored

Correct answer

C. size is elements stored; capacity is allocated slots

16 views

MCQSEXAM

Explanation

size() reports how many elements are actually stored, while capacity() reports how many could be stored before the next reallocation. Growth strategies usually double or multiply capacity by 1.5, so capacity is often larger than size and reserve() can set it in advance. Accessing an index between size and capacity is still out of bounds, since those slots hold no constructed objects.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? 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