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

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

问题描述

这篇文章的评论部分有一个关于使用 std::vector::reserve 的帖子() vs. 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 ;
}

我认为要在vector中写入元素,正确的做法是调用std::vector::resize(),不是 std::vector::reserve().

I believe that to write elements in the vector, the correct thing to do is to call std::vector::resize(), not 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;
}

我是对的,还是错的?VS2010 SP1 是对的,还是错的?

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.

reserve 之后,在你的情况下,你需要很多 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.

关于保留的一件事:如果您随后使用 push_back 添加元素,直到达到您保留的容量,任何现有的引用、迭代器或指向向量中数据的指针都将保持有效.所以如果我保留 1000 并且我的大小是 5,&vec[4] 将保持不变,直到向量有 1000 个元素.之后,我可以调用 push_back() 并且它会工作,但是之前存储的 &vec[4] 指针可能不再有效.

One thing about reserve: if you then add elements with push_back, until you reach the capacity you have reserved, any existing references, iterators or pointers to data in your vector will remain valid. So if I reserve 1000 and my size is 5, the &vec[4] will remain the same until the vector has 1000 elements. After that, I can call push_back() and it will work, but the stored pointer of &vec[4] earlier may no longer be valid.

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

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