c++ - 在 C++ 中对 STL vector 调用 resize() 时出现意外结果

标签 c++ vector stl containers

在下面的代码中,如果我调用 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 of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve(). 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/

相关文章:

c++如何将视频序列放入OpenCV中的vector <Mat>中?

c++ - remove_if() 编译错误

c++ - 如何在结构数组中显示学生姓名以及 GPA 高于平均水平的 ID

c++ - 使用 UDP 协议(protocol)发送结构并写入数据报

r - 如何从R中的向量返回5个最高值?

haskell - 如何确保 Data.Vector 的分摊 O(n) 级联?

c++ - 如何使用 STL 对数组进行 k-shuffle?

algorithm - 多索引中的多个唯一键

c++ - IBO 比 GL_TRIANGLE_STRIP 还差?

c++ - Doxygen 用调用图记录一个类中的所有函数?