问题描述
我想知道向量
的 push_back
和 insert 函数。
是否有结构差异?
是否有很大的性能差异?
Is there a really big performance difference(s)?
推荐答案
最大的区别是它们的功能。 push_back
总是在向量
和的末尾插入一个新元素insert
允许您选择新元素的位置。这会影响性能。 向量
元素只有在需要增加它的长度时才会在内存中移动,因为分配的内存太少。另一方面, insert
强制移动新元素的所选位置之后的所有元素。你只需要为它做一个地方。这就是为什么 insert
可能通常不如 push_back
有效。
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too less memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
这篇关于C ++向量插入& push_back差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!