Open In App

How to Add Element at the End of a Vector in C++?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors are dynamic arrays that provide flexibility and convenience over traditional arrays with additional features such as automatic resizing, ease of insertion and deletion of elements, etc. In this article, we’ll learn how to add an element at the end of a vector in C++.

For Example,

Input:
myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Output:
myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Add Element at the End of a Vector in C++

The vector containers have the std::vector::push_back() member function which is used to add an element to the end of the vector. We just need to pass the value to be added as an argument.

Syntax of std::vector::push_back()

myVector.push_back(value);

C++ Program to Add Element at the End of a Vector

C++




// C++ Program to demonstrate adding an element at the end
// of a vector using push_back()
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initializing a vector with some elements
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    cout << "Vector before adding an element: ";
    for (int element : myVector) {
        cout << element << " ";
    }
    cout << endl;
  
    // Adding an element at the end using push_back()
    myVector.push_back(6);
  
    // Printing the vector after adding the element
    cout << "Vector after adding an element: ";
    for (int element : myVector) {
        cout << element << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Vector before adding an element: 1 2 3 4 5 
Vector after adding an element: 1 2 3 4 5 6 

Time Complexity: O(1)
Auxilary Space : O(1)

We can also use std::vector::insert() along with the end iterator to insert the element at the end with the same time complexity.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads