简体   繁体   中英

Understanding Time complexity of STL vector from this chart

I came across thins site which states that insertion at the back of STL vector can either be O(1) or O(n). I believe insertion at the end should be O(1) for a vector. Could anyone clarify this and tell me what the author means by O(n). The author states that for STL vector insertion at the back Back: O(1) or O(n) . Which one is it ?

The complexity is required to be amortized constant.

That means that not every insertion necessarily takes the same length of time, but over the long term, it averages out to a constant regardless of the size of collection.

It does that by allocating a larger block when the current block gets full, and copying the data from the current block to a new one. The "trick" is that the block sizes increase in a geometric progression, so as the collection gets larger, copies happen progressively less often.

If you wanted to badly enough, you could actually make the time literally constant, not just amortized constant. When you need to allocate a larger block, you'd allocate a new block twice the size of the old one, insert the new item in its correct place in the new block, and copy exactly one item from the old block to the new one. Every time you inserted an item, you'd copy exactly one more item from the old block to the new one. Every insertion would require inserting one new item and copying one old item, so the complexity would be constant.

This would have a couple of disadvantages though. First, it would obviously keep both the old block and the new block in use instead of releasing the old block (almost) immediately after allocating the new one. Second, it would lose temporal locality, so when it copied one item from the old block to the new one, chances are pretty good that it wouldn't be in the cache. By copying the entire old block to the new one at once, you get much better cache utilization (at least as a rule).

Its O(1) if theres enough space, otherwise it has to allocate a bigger chunk and copy all the elements and THEN insert. So to answer your question: it's both.

The page you link to describes it as well as I could (although hopefully I'd spell reserve correctly):

std::vector has constant time (O(1)) back insertion provided no reallocation needs to take place (use reverse/capacity to allocate/check). When reallocation is necessary, all elements are copied (or moved, if possible) to a need memory location. It is guaranteed that back insertion is amortized constant, meaning: "if we perform a large amount of back insertions, the average time for back insertion is constant".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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