Open In App

Vector pop_back() in C++ STL

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

Output
1 4 6 

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;
}

Output
3 7 

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;
}

Output
Vector is empty!

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;
}

Output
0

Explanation: Using the while loop, an element is removed from the end of the vector till the vector becomes empty.


Next Article
Practice Tags :

Similar Reads