C++ Standard Library C++ STL Library

C++ <vector> - push_back() Function



The C++ vector::push_back function is used to add a new element at the end of the vector. Addition of new element always occurs after its current last element and every addition results into increasing the container size by one.

Syntax

void push_back (const value_type& val);
void push_back (const value_type& val);
void push_back (value_type&& val);

Parameters

val Specify the new element which need to be added in the vector.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::push_back function is used to add new elements in the vector called MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector;
  vector<int>::iterator it;

  //add new elements in the vector
  MyVector.push_back(10);
  MyVector.push_back(20);
  MyVector.push_back(30);
  MyVector.push_back(40);
  MyVector.push_back(50);


  cout<<"The vector contains:";
  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

The vector contains: 10 20 30 40 50

❮ C++ <vector> Library