c++ - 为什么 fill_n() 不适用于 vector.reserve()?

标签 c++ c++11 vector stl-algorithm

最近在学习标准库算法,对函数fill_n(iter, n, val)有疑问.此函数要求容器至少有 n 个元素,从 iter 开始。

测试代码如下:

// 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

为什么版本 1 代码有错误,而版本 2 & 3 却没有?

最佳答案

reserve只是保留空间,vector的大小不变。 begin 返回的迭代器不能递增到 vector 末尾之后,因为它是(不变的)大小决定 vector 末尾的位置,所以会出现错误。

关于c++ - 为什么 fill_n() 不适用于 vector.reserve()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34945292/

相关文章:

c++ - 我应该使用 boost::property_map 吗?

c++ - 使用 n 维 std::array 的大小初始化 constexpr std::array

c++ - 为什么在 "auto returning"函数中需要 decltype?

c++ - 在 C++ 中返回字符串和不同 vector 数据类型的映射

C++ - 将一个 Vector 附加到另一个 Vector,并删除重复项?

c++ - 错误 : invalid conversion from 'int' to 'const char*' [-fpermissive]

c++ - 将任意数量的任意类型的值组合成单个字符串的简单命令

c++ - nullptr_t 是默认的可构造类型吗?

c++ - 使用尽可能少的代码将非静态方法包装到带有 "this"参数绑定(bind)的 std::function

c++ - 找不到 C++ 类中的静态 vector