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()
?
Thanks a lot!
push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Basically, the vector::insert() function from the STL in C++ is used to insert elements or values into a vector container.
std::vector::push_back Adds a new element at the end of the vector, after its current last element.
Insertion in Vector of Vectors Elements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With