简体   繁体   English

在std :: vector :: resize和std :: vector :: push_back中摊销

[英]Amortizing in std::vector::resize and std::vector::push_back

We know that the reallocation mechanism takes care of allocating more memory that we actually need when calling std::vector::push_back() . 我们知道重新分配机制负责在调用std::vector::push_back()时分配更多我们实际需要的内存。 Usually the capacity grows with the multiplier 2x or with a golden ratio number ~1.618... 通常容量随着乘数2x或黄金比率~1.618而增长......

Assume, we add elements as follows: 假设,我们添加如下元素:

std::vector<int> v;
for(unsigned i = 0; i < 100000; ++i)
{
    v.resize(v.size() + 1);
}

Is it guaranteed that the capacity of the vector is "doubled" if the reallocation takes place? 如果进行重新分配,是否可以保证向量的容量“加倍”? In other words: would the "+1 resize" allocate the memory the same way as it is done for push_back . 换句话说:“+1 resize”是否会以与push_back相同的方式分配内存。

Or it is a pure implementation-depended thing? 或者它是一个纯粹的实现依赖的东西?

Is it guaranteed that the capacity of the vector is "doubled" if the reallocation takes place? 如果进行重新分配,是否可以保证向量的容量“加倍”?

No. The complexity of memory reallocation is amortized constant. 不会。内存重新分配的复杂性是不变的。 Whether the capacity of the object is doubled when needed or increased by another factor is implementation dependent. 对象的容量在需要时是加倍还是由另一个因子增加是依赖于实现的。

would the "+1 resize" allocate the memory the same way as it is done for push_back “+1 resize”是否会以与push_back相同的方式分配内存

Yes. 是。

std::vector::resize(size_type sz) appends sz - size() value-initialized elements to the sequence when sz is greater than size() . sz大于size()时, std::vector::resize(size_type sz)sz - size()值初始化元素附加到序列。 That is equivalent to: 这相当于:

 insert(end(), sz-size(), <value initialized object>);

std::vector::insert , std::vector::emplace , and std::vector::push_back have the same complexity for memory allocation - amortized constant. std::vector::insertstd::vector::emplacestd::vector::push_back具有相同的内存分配复杂度 - 摊销常量。

A vector is a sequence container that supports (amortized) constant time insert and erase operations at the end; 向量是一个序列容器,它在末尾支持(分期)恒定时间插入和擦除操作; [vector.overview] [vector.overview]

and

If size() < sz , appends sz - size() default-inserted elements to the sequence. 如果size()<sz,则将sz-size()默认插入元素追加到序列中。

for resize. 调整大小。 IMHO that means, yes, it is guaranteed that the capacity of the vector is "doubled" if the reallocation takes place 恕我直言,这意味着,是的,如果重新分配发生,保证向量的容量“加倍”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM