在下面的代码中,如果我调用 v.resize(n),程序会打印出 0 0 0 0 0 0 0 0 0 0,这不是我想看到的。但是,如果我将包含 v.resize(n) 的行注释掉,它将打印出 0 1 2 3 4 5 6 7 8 9,这是我想要看到的。为什么会这样?我的逻辑哪里出了问题?
#include <iostream>
#include <vector>
using namespace std;
int main( int argc , char ** argv )
{
int n = 10;
vector<int> v;
v.resize(n);
for( int i=0 ; i<n ; i++ )
{
v.push_back(i);
}
for( int i=0 ; i<n ; i++ )
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}
最佳答案
resize
确保 vector 恰好包含 n
元素,同时 push_back
将项目附加到 vector
, 因此在调整大小后占据 vector 的零之后添加了数字。如果您打印 vector 中的所有数字 ( < v.size()
) 而不是只打印第一个 n
,您可以看到它.
如您预期的那样运行的方法是 reserve()
:
Effects: A directive that informs a vector of a planned change in size, so that it can manage the storage allocation accordingly. After
reserve()
,capacity()
is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value ofcapacity()
otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument ofreserve()
. If an exception is thrown other than by the move constructor of a non-CopyInsertable type, there are no effects. (§23.3.6.3/2
)
关于c++ - 在 C++ 中对 STL vector 调用 resize() 时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18735910/