简体   繁体   English

插入STL载体

[英]Insertion into STL vector

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. 使用C ++ STL向量,我们正在构建N个元素的向量,由于某种原因,我们选择将它们插入向量的前面。 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. 向量元素前面的每个元素插入都会使所有现有元素移位1。这导致向量元素的整体移位(1 + 2 + 3 + ... + N),即(N / 2)(N +1)班次。

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? 我的问题是作者是怎么来的(1 + 2 + 3 + ... N),我认为应该是1 + 1 + 1..N,因为我们将一个元素移动到一个位置以开始变空?

Thanks! 谢谢!

From [vector.modifiers]/2 (which describes vector::insert ): [vector.modifiers]/2 (描述了vector::insert ):

Complexity: The complexity is linear in the number of elements inserted plus the distance to the end of the vector. 复杂度:复杂度是线性的,其插入元素的数量加上到向量末端的距离。

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. 第一次添加元素,要插入的元素为1,到末端的距离为0,所以复杂度为1 + 0 =1。第二次添加元素,要插入的元素与元素之间的距离。 end是1,所以复杂度是1 +1 =2。第三次,到端点的距离是2,所以复杂度是1 + 2 =3。这就是产生1 + 2 + 3 + ...的原因。作者正在描述的+ N模式。

At insertion n , there are n elements currently in the vector that needs to be shifted. 在插入n ,向量中当前需要移动n元素。

vector<int> values;
for (size_t i = 0; i < N; ++i)
{
     //At this point there are `i` elements in the vector that need to be moved
     //to make room for the new element
     values.insert(values.begin(), 0); 
}

The first Value is shifted N-1 times, each time a new value is inserted it has to move. 第一个值移动N-1次,每次插入新值时,它都必须移动。 The second value is shifted N-2 times because only N-2 values are added after it. 第二个值移位N-2次,因为在其后仅添加了N-2个值。 Next value is shifted N-3 and so on. 下一个值移位N-3,依此类推。 The last value is not shifted. 最后一个值不移位。

I don't know why the author speaks about N and not N-1. 我不知道为什么作者讲的是N而不是N-1。 But the reason for your confusion is, that the author counts the shifts of a single value and you count the amount of shift prozesses involving more than one single value shift. 但是,您感到困惑的原因是,作者计算了一个值的偏移量,并且您计算了涉及多个单个值偏移的偏移量。

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

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