I'm learning about the standard library algorithms recently and have a question about the function fill_n(iter, n, val)
. This function requires the container has at least n
elements starting from iter
.
Here is the testing code:
// Version 1, Error
vector<int> vec;
vec.reserve(10); // Only allocate space for at least 10 elements
fill_n(vec.begin(), 10, 0);
// Version 2, OK
vector<int> vec;
vec.resize(10); // Value initialized 10 elements
fill_n(vec.begin(), 10, 0);
// Version 3, OK
vector<int> vec;
fill_n(back_inserter(vec), 10, 0); // Push back 10 elements via back_inserter
Why the version 1 code is error while version 2 & 3 are not?
reserve
only reserves space, but the size of the vector remains unchanged. The iterator returned by begin
can not be incremented past the end of the vector, and because it is the (unchanged) size that determines where the end of the vector is, you get an error.