How to use push_back() and pop_back() vector functions in C++

The push_back() function

The push_back() function is used to insert an element at the end of a vector. This function is available in the <vector> header file.

Parameters

The push_back() function accepts one parameter, val, which specifies the value inserted at the end of the vector.

Return value

The push_back() function does not return anything.

Code

Now, let’s see the code and see how the push_back() function is used:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1,2,3};
cout << "Original Vector: ";
for(int x: vec)
cout << x << " ";
vec.push_back(5);
vec.push_back(10);
cout << "\nVector after pushing some values: ";
for(int x: vec)
cout << x << " ";
return 0;
}

Explanation

  • In lines 1 and 2, we import the required packages.
  • In lines 6 and 9, we create a vector that contains integers, and print the elements.
  • In lines 11 and 12, we call the push_back() function and insert some integer values.
  • In lines 13 and 15, we create and print the elements of the vector. We can see that the elements have been added at the end of the vector.

The pop_back() function

The pop_back() function is used to remove the last element from the vector. This function is available in the <vector> header file.

Parameters

The pop_back() function does not accept any parameters.

Return value

The pop_back() function does not return anything.

Code

Now, let’s look at the code and see how to use the pop_back() function:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1,2,3,4,5,6,7};
cout << "Original Vector: ";
for(int x: vec)
cout << x << " ";
vec.pop_back();
vec.pop_back();
cout << "\nVector after popping some values: ";
for(int x: vec)
cout << x << " ";
return 0;
}

Explanation

  • In lines 1 and 2, we import the required packages.
  • In lines 6 and 9, we create a vector that contains integers and print the elements.
  • In lines 11 and 12, we call the pop_back() function and insert some integer values.
  • In lines 13 and 15, we create and print the elements of the vector. We can see that two elements have been removed from the last of the vector.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources