std :: vector :: resize()vs. std :: vector :: reserve() [英] std::vector::resize() vs. std::vector::reserve()

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

问题描述

此帖的评论部分中有一个关于使用 std :: vector的主题:: reserve() std :: vector :: resize()

There is a thread in the comments section in this post about using std::vector::reserve() vs. std::vector::resize().

这是原始代码:

void MyClass::my_method()
{
    my_member.reserve(n_dim);
    for(int k = 0 ; k < n_dim ; k++ )
         my_member[k] = k ;
}

我相信在 / code>,正确的做法是调用 std :: vector :: resize() ,而不是 std :: vector :: reserve()

实际上,下面的测试代码在VS2010 SP1 :

In fact, the following test code "crashes" in debug builds in VS2010 SP1:

#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    v.reserve(10);
    v[5] = 2;

    return 0;
}

我是对的,还是我错了?

Am I right, or am I wrong? And is VS2010 SP1 right, or is it wrong?

推荐答案

原因有两种不同的方法:

There are two different methods for a reason:

std :: vector :: reserve 将分配内存,但不会调整向量的大小,它是之前的。

std::vector::reserve will allocate the memory but will not resize your vector, which will have a logical size the same as it was before.

std :: vector :: resize 实际上会修改矢量的大小,任何具有对象处于默认状态的空间。

std::vector::resize will actually modify the size of your vector and will fill any space with objects in their default state. If they are ints, they will all be zero.

保留后,在你的情况下,你将需要很多push_backs来写入元素5.
如果你不想这样做,那么在你的情况下,你应该使用调整大小。

After reserve, in your case, you will need a lot of push_backs to write to element 5. If you don't wish to do that then in your case you should use resize.

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

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