Learn two different ways to delete the last element from a vector in C++ i.e. using erase() and pop_back().

Remove last element from vector using vector::erase() in C++

In C++, the vector class provides a member function erase(), to remove a single or multiple elements.

iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);

To delete single element from a vector using erase() function, pass the iterator of the element to it, like erase(it). It will delete the element pointed by the iterator. It returns an iterator pointing to the new location of the next entity in vector i.e. the element followed the last deleted element.

To delete the last element from vector pass the iterator of the last element to the erase() function i.e.

vector<int> vecObj {11, 22, 33, 44, 55, 66, 77};

//Remove last element from vector
vecObj.erase(vecObj.end() - 1); 

It will delete the last element from vector. The (vector::end() – 1 ) returns the iterator of the last element in vector and we passed that to the erase() function. Therefore it deleted the last element from vector.

Checkout the complete example,

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> vecObj {11, 22, 33, 44, 55, 66, 77};

    //Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;

    //Remove last element from vector
    vecObj.erase(vecObj.end() - 1); 

    //Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;
}

Output:

11, 22, 33, 44, 55, 66, 77, 
11, 22, 33, 44, 55, 66,

It removed the last element from vector.

Remove last element from vector using vector::pop_back() in C++

In C++, the vector class provides a function pop_back() to remove the last element. It deletes the last element of vector and reduces its size by one. Let’s see an example,

 #include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> vecObj {11, 22, 33, 44, 55, 66, 77};

    //Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;

    //Remove last element from vector
    vecObj.pop_back(); 

    //Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;
}

Output:

11, 22, 33, 44, 55, 66, 77, 
11, 22, 33, 44, 55, 66, 

Read More

Summary

Today, we leaned about two different ways to remove the last element from vector in C++.

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.