vector的reserve()方法的行为 [英] Behavior of vector's reserve( ) method

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

问题描述

我想知道 std :: vector :: reserve()在以下情况下的行为:

I wanted to know the behavior of std::vector::reserve() in following situations:


  1. 假设 reserve(N)被立即多次调用。
    保留(N1)是否会被添加或覆盖?

  2. 保存(N1)被最新调用覆盖,
    然后如果最新的保留(Nn)需要较少的时隙?

  3. 在声明向量后,如果我们只需要 push_back()
    然后我们调用 reserve(N)。将 N

  4. 中是否已经包含 push_back() X
  5. 假设向量有一些X推送的元素,现在如果我们
    push_back() 1个元素(X + 1),那么该对象必须重新定位
    ;但我们还没有执行 push_back()。如果我们现在调用 reserve(),会发生什么
    ?对象会立即重定位
    吗?如果没有,那么如何保留空间?

  1. Suppose reserve(N) is called multiple times one after another immediately. Will the earlier reserve(N1) get added up or overwritten ?
  2. If the earlier reserve(N1) gets overwritten with the latest call, then what happens if the latest reserve(Nn) demands less number of slots ?
  3. After declaring vector if we have simply push_back() X elements, and then we call reserve(N). Will the already push_back() X elements counted in N ?
  4. Suppose, if the vector has some X pushed elements and now if we push_back() 1 more element (X+1), then that object would have to get relocated; but we haven't yet performed push_back(). What happens if we call reserve() now ? Will the object get relocated immediately ? If not, then how is the space reserved ?


推荐答案

()只是确保向量的已分配内存至少足够大以包含作为其参数传递的项目数。因此...

reserve() just makes sure that the vector's allocated memory is at least large enough to contain the number of items passed as its argument. Thus...


  1. 无论哪个最大值都是有效保留的最小容量。

  2. 请参阅#1。

  3. code>被调用以存储传递给 reserve()的项目数。

  1. Whichever the max value of all those passed will be the minimum resulting capacity effectively reserved.
  2. See #1.
  3. Yes.
  4. The vector allocates as much memory when reserve() is called as is necessary to store the number of items passed to reserve().






从实际标准引用:


To quote from the actual standard:

void reserve(size_type n)




如果 n 小于或等于 capacity(),则此调用无效。
否则,它是一个分配额外内存的请求。如果
请求成功,则 capacity()大于或等于 n ;
否则, capacity()不变。在任一情况下, size()
不变。

If n is less than or equal to capacity(), this call has no effect. Otherwise, it is a request for allocation of additional memory. If the request is successful, then capacity() is greater than or equal to n; otherwise, capacity() is unchanged. In either case, size() is unchanged.

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

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