How to Delete the Last Element from a Multiset in C++?
Last Updated :
28 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset< int > myMultiset
= { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
if (!myMultiset.empty()) {
myMultiset.erase(--myMultiset.end());
}
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)
Share your thoughts in the comments
Please Login to comment...