vector的reserve()方法的行为 [英] Behavior of vector's reserve( ) method
问题描述
我想知道 std :: vector :: reserve()
在以下情况下的行为:
I wanted to know the behavior of std::vector::reserve()
in following situations:
- 假设
reserve(N)
被立即多次调用。
保留(N1)
是否会被添加或覆盖? - 保存(N1)被最新调用覆盖,
然后如果最新的保留(Nn)
需要较少的时隙? - 在声明
向量
后,如果我们只需要push_back()
,
然后我们调用reserve(N)
。将N
? - 假设
向量
有一些X推送的元素,现在如果我们
push_back()
1个元素(X + 1),那么该对象必须重新定位
;但我们还没有执行push_back()
。如果我们现在调用reserve()
,会发生什么
?对象会立即重定位
吗?如果没有,那么如何保留空间?
中是否已经包含
push_back()
X - Suppose
reserve(N)
is called multiple times one after another immediately. Will the earlierreserve(N1)
get added up or overwritten ? - If the earlier
reserve(N1)
gets overwritten with the latest call, then what happens if the latestreserve(Nn)
demands less number of slots ? - After declaring
vector
if we have simplypush_back()
X elements, and then we callreserve(N)
. Will the alreadypush_back()
X elements counted inN
? - Suppose, if the
vector
has some X pushed elements and now if wepush_back()
1 more element (X+1), then that object would have to get relocated; but we haven't yet performedpush_back()
. What happens if we callreserve()
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。
- 是
- code>被调用以存储传递给
reserve()
的项目数。
- Whichever the max value of all those passed will be the minimum resulting capacity effectively reserved.
- See #1.
- Yes.
- The vector allocates as much memory when
reserve()
is called as is necessary to store the number of items passed toreserve()
.
从实际标准引用:
To quote from the actual standard:
void reserve(size_type n)
如果
n
小于或等于capacity()
,则此调用无效。
否则,它是一个分配额外内存的请求。如果
请求成功,则capacity()
大于或等于n
;
否则,capacity()
不变。在任一情况下,size()
是
不变。
If
n
is less than or equal tocapacity()
, this call has no effect. Otherwise, it is a request for allocation of additional memory. If the request is successful, thencapacity()
is greater than or equal ton
; otherwise,capacity()
is unchanged. In either case,size()
is unchanged.
这篇关于vector的reserve()方法的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!