With a C++ STL vector we are building a vector of N elements and for some
reason we chose to insert them at the front of the vector. Every element insertion at the front of a vector forces the shift of all existing elements by 1. This results in (1+2+3+…+N) overall shifts of vector elements, which is (N/2)(N+1) shifts.
My question is how the author came with (1+2+3+…N), I thought it should be 1+1+1..N as we are moving one element at one position to get empty at beginning?
Thanks!
From
[vector.modifiers]/2(which describesvector::insert):Each time that you add an element the distance to the end of the vector is increased by one.
The first time that you add an element, there is 1 to be inserted and the distance to the end is 0, so the complexity is 1 + 0 = 1. The second time, there is 1 to be inserted, and the distance to the end is 1, so the complexity is 1 + 1 = 2. The third time, the distance to the end is 2, so the complexity is 1 + 2 = 3. This is what creates the 1 + 2 + 3 + … + N pattern that the author is describing.