In this tutorial, we will learn about pop_back() member function of vector in C++.

In C++, the std::vector is a sequential container that works like a dynamic array that can resize itself automatically when an element is added or removed. One of the most used member function f vector class is push_back(), which removes the last element from the vector.

Syntax of vector::pop_back()

The pop_back() member function in C++ has a straightforward syntax:

void pop_back();

This function does not take any parameters and does not return any value.

Parameters of vector::pop_back()

Since pop_back() does not require any parameters, it’s simple and easy to use. The function operates directly on the vector from which it is called.

Return Value of vector::pop_back()

The pop_back() function does not return a value. Its only purpose is to remove the last element from the vector, effectively reducing the vector’s size by one.

Examples of vector::pop_back(): Remove the Last Element from a Vector

In this example, we will demonstrate how to use pop_back() to remove the last element from a vector.

First, we will create a vector of integers and initialize it some default values. Then, we will remove the last element from the vector by calling the pop_back() function. After calling the pop_back function, the size of the vector will be reduced by one.

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {56, 87, 89, 91, 44};

    // Displaying original vector
    std::cout << "Original vector: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }
    std::cout << std::endl;

    // Removing the last element
    numbers.pop_back();

    // Displaying vector after pop_back
    std::cout << "Vector after pop_back: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }

    return 0;
}

Output

Original vector: 56 87 89 91 44 
Vector after pop_back: 56 87 89 91

In this code, we first create a std::vector<int> named numbers and initialize it with some integers. We then use pop_back() to remove the last element of the vector. The size of the vector is reduced by one, and the last element is no longer part of the vector. The output of the program will display the vector before and after the pop_back() operation.

Summary

This article, explained the simplicity and effectiveness of pop_back() in modifying the size of a vector by removing its last element.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.