Using C++ vector::insert() to add to end of vector
Solution 1
a.push_back(x)
is defined to have identical semantics to (void)a.insert(a.end(),x)
for sequence containers that support it.
See table 68 in ISO/IEC 14882:2003 23.1.1/12 [lib.sequence.reqmts].
Regarding the running time of vector.push_back(x)
vs. vector.insert(vector.end(), x)
consider the emphasized part:
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 constant time.
Solution 2
There is a slight difference that push_back
returns void
whether insert
returns iterator
to element just inserted.
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.
Comments
-
Nick Van Hoogenstyn almost 2 years
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 usepush_back()
. But to keep my code looking nice, I'd like to exclusively useinsert()
, 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 isv.end()
, wherev
is my vector, will this work the same aspush_back()
?Thanks a lot!
-
Saman about 8 yearsQuick question, in terms of performance , I wonder if pusk_back works faster? I tested something showing insert is kind of slow . I just wanted to make sure... Thanks
-
peterh almost 8 yearspush_back() doesn't gives back the iterator of the newly inserted element. std::list<T>::end() will give back a dead iterator.
-
Jon McClung about 5 yearsAnswer would be better if you included the section of the standard you reference
-
CB Bailey about 5 years@JonMcClung: Um, but the answer already includes that information?
-
Jon McClung about 5 yearsI meant as a quote. I don't know how to look up a random section of the standard from the chapter marker or whatever you gave.