When you do x.reserve(10)
you only set the capacity to ten elements, but the size is still zero.
(当您执行x.reserve(10)
,仅将容量设置为十个元素,但大小仍为零。)
That means then you use the index operator in your loop you will go out of bounds (since the size is zero) and you will have undefined behavior .
(这意味着,然后在循环中使用index运算符将超出范围(因为大小为零),并且将具有未定义的行为 。)
If you want to set the size, then use either resize
or simply tell it when constructing the vector:
(如果要设置大小,则在构造向量时可以使用resize
或简单地告诉它:)
std::vector<double> x(10);
As for the capacity of the vector, when you set it (using eg reserve
) then it allocates the memory needed for (in your case) ten elements.
(至于向量的容量 ,当您设置它(使用例如reserve
)时,它将为(在您的情况下)十个元素分配所需的内存。)
That means when you do push_back
there will be no reallocations of the vector data. (这意味着当您执行push_back
,将不会重新分配矢量数据。)
If you do not change the capacity, or add elements beyond the capacity, then each push_back
may cause a reallocation of the vector data.
(如果您不更改容量或添加超出容量的元素,则每个push_back
可能导致重新分配矢量数据。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…