Why does using push_back on a vector declared with size result in a vector of zeros?

That’s because push_back puts new elements onto the end of the vector.

You can see the effect by running i to 9: the negative numbers will occupy v[5] to v[9].

Writing

std::vector<int> v{-1, -2, -3, -4, -5};

instead is a particularly elegant fix.

Leave a Comment