C++ Unordered_set:: equal_range() Function



The C++ std::unordered_set::equal_range() function is used to return the bounds of a range that includes all the elements that equal to k. The range will include atleast one element if the unordered_set containers keys are unique.

The range is defined by the two iterators, with the first pointing to the first element of the wanted range and the second pointing past the last element of the range.

Syntax

Following is the syntax of std::unordered_set::equal_range.

pair<iterator,iterator> equal_range( const Key& key );
pair<const_iterator,const_iterator> equal_range ( const key_type& k ) const;

Parameters

  • k − It indicates the value to be compared.

Return Value

This function returns a pair of bounds, with pair::first member as the lower bound of the range and pair::second member as the upper bound of the range.

Example 1

In the following example, we are going to demonstrate the usage of unordered_set::equal_range() function.

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet;
   uSet.insert({ 5, 30, 180 });
	
   auto range = uSet.equal_range(30);
   if (range.first != uSet.end()) {
      for (; range.first != range.second; ++range.first)
         cout << *range.first << endl;
   }
   else
      cout << "Element does not exist";
   return 0;
}

Output

If we run the above code it will generate the following output −

30

Example 2

Consider the following example, where we are going to use the equal_range() function to test the equal_range for a given key if it exist.

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet;
   uSet.insert({ 5, 30, 180 });
	
   auto range = uSet.equal_range(50);
   if (range.first != uSet.end()) {
      for (; range.first != range.second; ++range.first)
         cout << *range.first << endl;
   }
   else
      cout << "Element does not exist";
   return 0;
}

Output

Following is the output of the above code −

Element does not exist

Example 3

Leet's look at the following example, where we are going to use the equal_range() function to find the lower and upper bounds of the specified key.

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet = { 5, 30, 50, 180 };
   unordered_set<int>::iterator it;
	
   cout<<"uSet contains:";	
   for(auto &it: uSet)
      cout<<" "<<it;
   //finding the bound range of 50;
   pair<unordered_set<int>::iterator, unordered_set<int>::iterator> bound;
   bound = uSet.equal_range (30);
 	
   cout<<"\nLower bound is: "<<*bound.first<<endl;  
   cout<<"Upper bound is: "<<*bound.second<<endl;  
   return 0;
}

Output

Output of the above code is as follows −

uSet contains: 180 50 30 5
Lower bound is: 30
Upper bound is: 5
Advertisements