How to Add Element at the End of a Vector in C++?
Last Updated :
09 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
cout << "Vector before adding an element: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
myVector.push_back(6);
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.
Share your thoughts in the comments
Please Login to comment...