C++ Standard Library C++ STL Library

C++ unordered_set - equal_range() Function



The C++ unordered_set::equal_range function returns the bounds of a range which includes all elements in the unordered_set 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.

As a unordered_set contains unique elements, therefore the range will contain a single element at most. 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_set::equal_range function returns the bounds of a range for specified value in uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{60, 10, 20, 80, 90};
  unordered_set<int>::iterator it;

  cout<<"uSet contains:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;

  //finding bound range of 20
  pair<unordered_set<int>::iterator,
       unordered_set<int>::iterator> pit;
  pit = uSet.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:

uSet contains: 90 80 20 10 60
The lower bound point is: 20
The upper bound point is: 10

Example:

Lets consider another example where equal_range() function is used to specify bound range to delete elements from the unordered_set.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{60, 10, 20, 80, 90};
  unordered_set<int>::iterator it;

  cout<<"uSet contains:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;

  //finding bound range of 20
  pair<unordered_set<int>::iterator,
       unordered_set<int>::iterator> pit;
  pit = uSet.equal_range(20);

  //erasing the elements from the set
  uSet.erase(pit.first, pit.second);

  cout<<"\nuSet contains:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

uSet contains: 90 80 20 10 60
uSet contains: 90 80 10 60

❮ C++ <unordered_set> Library

5