Last Updated : 29 Aug, 2024
The unordered_multiset::erase() function is a built-in function in C++ STL which is used to remove either a single element or, all elements with a definite value or, a range of elements ranging from start(inclusive) to end(exclusive). This decreases the size of the container by the number of elements removed.
Syntax
- unordered_multiset_name.erase(iterator position)
- unordered_multiset_name.erase(iterator start, iterator end)
- unordered_multiset_name.erase(key_value)
Parameters
This function has three versions.
Return Value
The 1st and 2nd version of the function as shown in the above syntax returns an iterator immediately following the last element erased. The 3rd version returns the number of element erased. Below programs illustrate the unordered_multiset::erase() function:
Program 1
CPP
// C++ program to illustrate the
// unordered_multiset::erase() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_multiset<int> samplemultiSet;
// Inserting elements
samplemultiSet.insert(10);
samplemultiSet.insert(5);
samplemultiSet.insert(15);
samplemultiSet.insert(20);
samplemultiSet.insert(25);
samplemultiSet.insert(10);
samplemultiSet.insert(15);
samplemultiSet.insert(20);
// Erases a particular element by its position
samplemultiSet.erase(samplemultiSet.begin());
// Displaying the set after removal
for (auto it = samplemultiSet.begin();
it != samplemultiSet.end(); it++) {
cout << *it << " ";
}
// erases a range of elements,
// here all the elements
samplemultiSet.erase(samplemultiSet.begin(),
samplemultiSet.end());
cout << "\nMultiSet size: " << samplemultiSet.size();
return 0;
}
Output
20 20 15 15 5 10 10 MultiSet size: 0
Time Complexity: O(n), where n
is the number of occurrences of the value 10
.
Auxiliary Space: O(1)
Program 2
CPP
// C++ program to illustrate the
// unordered_multiset::erase() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_multiset<int> samplemultiSet;
// Inserting elements
samplemultiSet.insert(10);
samplemultiSet.insert(5);
samplemultiSet.insert(15);
samplemultiSet.insert(20);
samplemultiSet.insert(25);
samplemultiSet.insert(10);
samplemultiSet.insert(15);
samplemultiSet.insert(20);
// Erases all elements of value 10
samplemultiSet.erase(10);
// Displaying the set after removal
for (auto it = samplemultiSet.begin();
it != samplemultiSet.end(); it++) {
cout << *it << " ";
}
return 0;
}
Output
25 20 20 15 15 5
Time Complexity: O(n), where n
is the number of occurrences of the value 10
.
Auxiliary Space: O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4