简体   繁体   English

具有反向和pop / push_back成本的STL向量

[英]STL vector with reverse and pop/push_back cost

I am not exactly good to come up with algorithm costs, so here I am asking. 我提出算法成本并不是很好,所以我在这里问。

Here is a vector initially initialized with 1000 elements: 这是一个最初用1000个元素初始化的向量:

vector<unsigned int> mFreeIndexes(1000);

I will continuously pop_back/push_back elements to the vector, but never push_back over 1000 (so never force vector to reallocate). 我将持续pop_back / push_back元素到向量,但永远不会push_back超过1000(所以永远不要强制向量重新分配)。

In this case will the pop_back/push_back operations be O(1) or O(n)? 在这种情况下,pop_back / push_back操作是O(1)还是O(n)?

From the C++ standard 23.3.7.5: 从C ++标准23.3.7.5开始:

void push_back(const T& x); void push_back(const T&x);

void push_back(T&& x); void push_back(T && x);

Remarks: Causes reallocation if the new size is greater than the old capacity (...) 备注:如果新大小大于旧容量(...),则会导致重新分配

Note that it doesn't say that it can't reallocate in the other scenario but this would be a very unusual implementation of the standard. 请注意,它并没有说它不能在其他场景中重新分配,但这将是标准的一个非常不寻常的实现。 I think you can safely assume that push_back won't reallocate when there's still capacity. 我认为你可以放心地假设当仍有容量时push_back不会重新分配。

The thing with pop_back is a bit more complicated. pop_back的东西有点复杂。 The standard does not say anything about reallocation in the pop_back context. 该标准没有说明pop_back上下文中的重新分配。 But it seems to be a common implementation (with no know exception) that pop_back does not reallocate. 但它似乎是pop_back不重新分配的常见实现(没有已知的异常)。 There are some guarantees though, see this: 虽然有一些保证,请看:

Can pop_back() ever reduce the capacity of a vector? pop_back()能否减少向量的容量? (C++) (C ++)

Anyway as long as you don't go over predefined size you are safe to assume that no reallocation happens and the complexity is indeed O(1). 无论如何,只要你没有超过预定义的大小,你可以安全地假设没有重新分配,复杂性确实是O(1)。

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

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