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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With