Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector's insert & push_back difference

Tags:

c++

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)?

like image 794
totten Avatar asked Nov 10 '12 17:11

totten


People also ask

How do I use insert in STL?

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.

How do you add an element to a vector in C++?

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.

What is insert function in C++?

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.

How do you add an element to a vector at a specific position?

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.


1 Answers

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.

like image 56
Adam Sznajder Avatar answered Sep 23 '22 09:09

Adam Sznajder