On an empty std::vector<int> v, what do v.reserve(100) and v.resize(100) each produce?
A
Both set only capacity, differing solely in the exception guarantees offered when a reallocation fails
B
reserve sets capacity to 100 with size still 0; resize sets size and capacity to 100 with value-initialised elements
Correct answer
C
Both set size to 100, but reserve leaves the new elements uninitialised until each element is written
D
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
⚔️
Challenge a friend on C++ and Object-Oriented Programming
Same MCQs, timed, live leaderboard. Send the link on WhatsApp – no sign-up needed.
Create challenge
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
Doubts & discussionNot sure why the answer is B? Ask here and get an explanation.
Ask a doubt about this MCQ
‹ Previous MCQ class D : public A, public B { Mem1 m1; Mem2 m2; public: D() : m2(2), m1(1), B(), A() {} }; In what order are bases and members initialised, and destroyed? Next MCQ › For objects a and b of class T, which special member is used by T b = a; and which by b = a; when b already exists?