使用 C++ vector::insert() 添加到向量的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5960979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using C++ vector::insert() to add to end of vector
提问by Nick Van Hoogenstyn
I'm writing a little piece of code where I'll have to insert values into a C++ STL vector at a certain place depending on values in the vector elements. I'm using the insert()
function to accomplish this. I realize that when I want to add a new element to the end of the vector, I could simply use push_back()
. But to keep my code looking nice, I'd like to exclusively use insert()
, which takes as input the iterator pointing to the element after the desired insertion point and the value to be inserted. If the value of the iterator passed in as an argument is v.end()
, where v
is my vector, will this work the same as push_back()
?
我正在编写一小段代码,我必须根据向量元素中的值在某个位置将值插入到 C++ STL 向量中。我正在使用该insert()
功能来完成此操作。我意识到当我想在向量的末尾添加一个新元素时,我可以简单地使用push_back()
. 但是为了让我的代码看起来不错,我想专门使用insert()
,它将指向所需插入点之后的元素的迭代器和要插入的值作为输入。如果作为参数传入的迭代器的值是v.end()
,v
我的向量在哪里,这与push_back()
?
Thanks a lot!
非常感谢!
回答by CB Bailey
a.push_back(x)
is definedto have identical semantics to (void)a.insert(a.end(),x)
for sequence containers that support it.
a.push_back(x)
被定义为与(void)a.insert(a.end(),x)
支持它的序列容器具有相同的语义。
See table 68 in ISO/IEC 14882:2003 23.1.1/12 [lib.sequence.reqmts].
参见 ISO/IEC 14882:2003 23.1.1/12 [lib.sequence.reqmts] 中的表 68。
Regarding the running time of vector.push_back(x)
vs. vector.insert(vector.end(), x)
consider the emphasized part:
关于vector.push_back(x)
vs.的运行时间,vector.insert(vector.end(), x)
考虑强调的部分:
Table 68 lists sequence operations that are provided for some types of sequential containers but not others. An implementation shall provide these operations for all container types shown in the ‘‘container'' column, and shall implement them so as to take amortized constanttime.
表 68 列出了为某些类型的顺序容器提供但不为其他类型提供的顺序操作。实现应为“容器”列中显示的所有容器类型提供这些操作,并应实现它们以占用固定的分摊时间。
回答by neuront
There is a slight difference that push_back
returns void
whether insert
returns iterator
to element just inserted.
push_back
返回void
是否insert
返回iterator
到刚插入的元素略有不同。
By the way, there is another way to verify whether they do the same thing: compile the following codes
顺便说一下,还有一种方法可以验证它们是否做同样的事情:编译以下代码
int main()
{
std::vector<int const> v;
v.push_back(0);
return 0;
}
the compiler will print a lot of annoying messages, just read and you will find push_back
calls insert
(if not, try compiling v.insert(v.end(), 0)
to see if they call the same inserting function) in the end.
编译器会打印很多烦人的消息,只要阅读,你就会在最后找到push_back
调用insert
(如果没有,请尝试编译v.insert(v.end(), 0)
以查看它们是否调用了相同的插入函数)。