The difference between push_back and insert in C++

The push_back and insert functions insert elements into many STL containers like the vector, list, and deque. In this article, we will compare the differences between the two with the help of a vector container. However, the principle remains the same for other containers which support these two operations.

The push_back() function:

The push_back() function is used to add elements to the end of the sequential container. The only instance of this function is inserting a value at the back and it has no other overloads.

The following code illustrates the push_back() operation on a vector

#include <iostream>
#include <vector>
int main() {
     std::vector<int> a={0}; //empty vector
     for(int i=1;i<5;i++)
     {
         a.push_back(i); //inserting first 4 natural numbers
     }
     std::cout<<"The vector is:"<<std::endl;
     for(int x:a)
     {
         std::cout<<x<<" ";
     }
}
Output:
The vector is:
0 1 2 3 4

The insert() function:

The insert function on the other hand is used to insert elements in the middle of the container. It can insert in a specific position or it can fill a particular range. It has multiple overloads to insert an element in the middle of the container.

The following code illustrates some of the overloads of insert() on a vector

#include <iostream>
#include <vector>



void printvec(std::vector<int> &a) // helper function to print the vector
{
  for (int x : a)
  {
    std::cout << x << " ";
  }
  std::cout << "\n";
}

int main()
{
  std::vector<int> a = { 1,2,3,4,5 };

  // inserting in a particular position
  a.insert(a.begin() + 1, 10);
  std::cout << "The vector after insertion is:";
  printvec(a);
  //inserting multiple elements in a particular position
  a.insert(a.begin() + 1, 2, 20);
  std::cout << "The vector after insertion is:";
  printvec(a);
  //inseting  a range(array) into vector
  int arr[3] = { 40,50,60 };

  a.insert(a.begin(), arr, arr + 3);
  std::cout << "The vector after insertion is:";
  printvec(a);
}
Output:
The vector after insertion is:1 10 2 3 4 5 
The vector after insertion is:1 20 20 10 2 3 4 5 
The vector after insertion is:40 50 60 1 20 20 10 2 3 4 5 

The differences between push_back() and insert():

  • The main difference between the two functions is that push_back() can insert at the end of the container but insert and inserted anywhere in the container.
  • push_back() runs faster because the iterator to the last element is usually maintained and thus runs in amortized constant time, for inserting in the middle the elements have to be shifted and inserted which takes linear time compared to the constant time of the push_back().
  • The insert() function has several overloads whereas the push_back() has no overloads.

Leave a Reply

Your email address will not be published. Required fields are marked *