-->

Why fill_n() does not work with vector.reserve()?

2019-02-25 00:12发布

问题:

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?

回答1:

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.



回答2:

Version 1 does NOT work because:

std::reserve modifies the capacity of the vector and NOT it's size. std::fill_n requires that the container have the correct size beforehand.

Version 2 works because:

std::resize does modify the size of the vector and not just its capacity.

Version 3 works because:

std::back_inserter will call push_back on the vector which adds to the vector and modifies it's size accordingly.



回答3:

reserve does not initialize anything. It just reserve some space so no reallocation happens each time new item is pushed. So the solution to tell fill_n to push its result directly to the vector at the end for example.

Change this:

// Version 1, Error
vector<int> vec;
vec.reserve(10);  // Only allocate space for at least 10 elements
fill_n(vec.begin(), 10, 0);

To:

// Version 1, Corrected
vector<int> vec;
vec.reserve(10);  // Only allocate space for at least 10 elements
fill_n(std::back_inserter(vec), 10, 0);