为什么fill_n()与vector.reserve()不兼容? [英] Why fill_n() does not work with vector.reserve()?
问题描述
我最近正在学习标准库算法,并对功能 <代码> fill_n(iter,n,val) .此功能要求容器从 iter
开始至少具有 n
个元素.
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
.
这是测试代码:
// 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个不是吗?
Why the version 1 code is error while version 2 & 3 are not?
推荐答案
reserve
仅保留空间,但是向量的大小保持不变. begin
返回的迭代器不能增加到向量的末尾,并且因为(不变的)大小决定了向量的末尾在哪里,所以会出现错误.
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.
这篇关于为什么fill_n()与vector.reserve()不兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!