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

早过忘川 提交于 2019-12-01 20:30:40

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.

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.

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