C++ unordered_multiset - equal_range() Function
The C++ unordered_multiset::equal_range function returns the bounds of a range which includes all elements in the unordered_multiset container that are equivalent to specified value. It returns a pair, with pair::first member as the lower bound of the range, and pair::second member as the upper bound of the range.
If no match is found, it will return the range with end as both its lower and upper range bounds.
Syntax
pair<const_iterator,const_iterator> equal_range (const key_type& k) const; pair<iterator,iterator> equal_range (const key_type& k);
Parameters
val |
Specify value to compare. |
Return Value
Returns a pair, with pair::first member as the lower bound of the range, and pair::second member as the upper bound of the range.
Time Complexity
Average case: Constant i.e, Θ(1).
Worst case: Linear in container sizei.e, Θ(n).
Example:
In the example below, the unordered_multiset::equal_range function returns the bounds of a range for specified value in uMSet.
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_multiset<int> uMSet{30, 20, 20, 40, 20, 40, 50}; unordered_multiset<int>::iterator it; cout<<"uMSet contains:"; for(it = uMSet.begin(); it != uMSet.end(); ++it) cout<<" "<<*it; //finding bound range of 20 pair<unordered_multiset<int>::iterator, unordered_multiset<int>::iterator> pit; pit = uMSet.equal_range(20); cout<<"\nThe lower bound point is: "<<*pit.first<<"\n"; cout<<"The upper bound point is: "<<*pit.second<<"\n"; return 0; }
The output of the above code will be:
uMSet contains: 50 40 40 20 20 20 30 The lower bound point is: 20 The upper bound point is: 30
Example:
Lets consider another example where equal_range() function is used to specify bound range to delete elements from the unordered_multiset.
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_multiset<int> uMSet{30, 20, 20, 40, 20, 40, 50}; unordered_multiset<int>::iterator it; cout<<"uMSet contains:"; for(it = uMSet.begin(); it != uMSet.end(); ++it) cout<<" "<<*it; //finding bound range of 20 pair<unordered_multiset<int>::iterator, unordered_multiset<int>::iterator> pit; pit = uMSet.equal_range(20); //erasing the elements from the multiset uMSet.erase(pit.first, pit.second); cout<<"\nuMSet contains:"; for(it = uMSet.begin(); it != uMSet.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
uMSet contains: 50 40 40 20 20 20 30 uMSet contains: 50 40 40 30
❮ C++ <unordered_set> Library