Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Time complexity of STL vector from this chart

Tags:

c++

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 ?

like image 648
Rajeshwar Avatar asked Dec 05 '22 07:12

Rajeshwar


2 Answers

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).

like image 129
Jerry Coffin Avatar answered Dec 09 '22 14:12

Jerry Coffin


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.

like image 42
Borgleader Avatar answered Dec 09 '22 14:12

Borgleader