Practice mode C++

If std::vector::push_back causes the vector’s size to exceed its capacity, what happens to existing iterators and references to its elements?

Correct answer D. All of them are invalidated

Explanation

When the new size exceeds capacity, the vector allocates a larger block and moves or copies its elements there, so every iterator, pointer and reference to the old elements becomes invalid. If no reallocation occurs, only end() is invalidated. Calling reserve() in advance avoids reallocation and keeps existing iterators valid while you append.

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.