Last Updated : 23 Jul, 2025
In C++, the vector pop_back() is a built-in method used to remove the last element from a vector. It reduces the size of the vector by one, but the capacity remains unchanged.
Let’s take a look at an example that illustrates the vector pop_back() method:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 9};
// Remove the last element
v.pop_back();
for (int i : v)
cout << i << " ";
return 0;
}
This article covers the syntax, usage, and common examples of the vector pop_back() method in C++:
Syntax of Vector pop_back()The vector pop_back() is a member method of the std::vector class defined inside the <vector> header file.
v.pop_back();
This function neither takes any parameter nor returns any value.
Examples of Vector pop_back()The following examples demonstrate the use of the vector pop_back() function for different purposes:
Remove Last Element from a Vector C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {3, 7, 9};
// Remove the last element
v.pop_back();
for (int i : v)
cout << i << " ";
return 0;
}
Use pop_back() on an Empty Vector C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v;
// Try to remove element from empty vector
if (!v.empty())
v.pop_back();
else
cout << "Vector is empty!";
return 0;
}
Explanation: Before calling pop_back(), it is a good practice to check if the vector is empty using the vector empty() method, as pop_back() on an empty vector leads to undefined behavior.
Delete All Elements from a Vector C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {3, 7, 9};
// Remove elements till vector is empty
while(!v.empty())
v.pop_back();
cout << v.size();
return 0;
}
Explanation: Using the while loop, an element is removed from the end of the vector till the vector becomes empty.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4