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

寵の児 提交于 2019-12-20 02:28:32

问题


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);


来源:https://stackoverflow.com/questions/34945292/why-fill-n-does-not-work-with-vector-reserve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!