注意vector :: reserve? [英] Be careful of vector::reserve?

查看:152
本文介绍了注意vector :: reserve?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做这样的事情:

#include <vector>
#include <algorithm>

int main()
{
    int l[] = {1,2,3,4};
    vector<int> vi(4);
    copy(l, l+4, vi.begin());

    do_stuff();
}

上述代码可以编译和运行,没有错误。然后我把它改为:

The above code can compile and run without no errors. Then I changed it into this:

int main()
{
    int l[] = {1,2,3,4};
    vector<int> vi;
    vi.reserve(4);  //different from the above code
    copy(l, l+4, vi.begin());

    do_stuff();
}

根据代码,我更改了 vector< int> ; vi(4); into vector< int> vi; vi.reserve(4); 出现问题,即更改的代码可以编译,但运行时出现seg fault。

According to the code, I changed vector<int> vi(4); into vector<int> vi; vi.reserve(4);, but the problem comes, that is, the changed code can compile, but a seg-fault occurs when it runs.

根据 gdb ,seg错误发生在函数 do_stuff();

According to gdb, the seg-fault occurs in function do_stuff();.

为什么?我做的改变是重要的吗?我不能在这里使用 reserve

Why is that? Does the change I made matter? Can't I use reserve here?

推荐答案

$ c> reserve()方法只分配内存,但保留未初始化。它只影响 capacity(),但 size()将不会改变。

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged.

如果您想创建多个实例,您应该使用 resize()分配内存,许多实例作为参数传递给 resize()

If you want to create as many instances you should use resize() which allocates memory, and also creates as many instances as the argument passed to resize().

这篇关于注意vector :: reserve?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆