Horje
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++

// 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)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Frequency of an Element in a Set in C++? How to Find the Frequency of an Element in a Set in C++?
How to Create a Multimap of Vectors in C++? How to Create a Multimap of Vectors in C++?
How to Delete Multiple Elements from a Vector in C++? How to Delete Multiple Elements from a Vector in C++?
How to Declare a Static Member Function in a Class in C++? How to Declare a Static Member Function in a Class in C++?
How to Create a Set of Pairs in C++? How to Create a Set of Pairs in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11