Open In App

How to Delete the Last Element from a Multiset in C++?

In C++, a multiset is a container that can store multiple elements, including duplicates. In this article, we will learn how to delete the last element from a multiset in C++.

Example:



Input:
myMultiset = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 }
Element to delete = 4

Output:
myMultiset = { 1, 2, 2, 3, 3, 3, 4, 4, 4 }

Erase the Last Element from a Multiset in C++

To delete the last element from a multiset, we can use the std::multiset::end() function to get an iterator to the last element. Then we can pass this iterator to the std::multiset::erase() function to remove only the last element.

If you want to remove all the occurrences of the last element, we can pass the value of the element instead of the iterator to the erase() function.



C++ Program to Erase the Last Element from a Multiset in C++

The below program demonstrates how we can delete the last element from a multiset.




// C++ Program to Delete the Last Element from a Multiset
#include <iostream>
#include <set>
  
using namespace std;
  
int main()
{
    // Define a multiset
    multiset<int> myMultiset
        = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
  
    // If the multiset is not empty, erase the last element
    if (!myMultiset.empty()) {
        myMultiset.erase(--myMultiset.end());
    }
  
    // Print the multiset
    cout << "Multiset: ";
    for (int elem : myMultiset)
        cout << elem << " ";
    cout << endl;
  
    return 0;
}

Output
Multiset: 1 2 2 3 3 3 4 4 4 

Time Complexity: O(N) where N is the numbers of elements in the multiset.
Auxiliary Space: O(1)

Article Tags :