I want to know what are difference(s) between vector
's push_back
and insert
functions.
Is there a structural difference(s)?
Is there a really big performance difference(s)?
vector insert() function in C++ STL Parameter:The function accepts two parameters specified as below: position – It specifies the iterator which points to the position where the insertion is to be done. val – It specifies the value to be inserted.
To add elements to vector, you can use push_back() function. push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.
insert() function is an inbuilt function in C++ STL, which is defined in <set> header file. This function is used to insert elements in the set container. when we insert the element the size of the container is increased by the number of the elements inserted.
Inserting a single element at specific position in vectoriterator insert (const_iterator pos, const value_type& val); iterator insert (const_iterator pos, const value_type& val); It Inserts a copy of give element “val”, before the iterator position “pos” and also returns the iterator pointing to new inserted element.
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 little 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
.
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