C++ Standard Library C++ STL Library

C++ set - equal_range() Function



The C++ set::equal_range function returns the bounds of a range which includes all elements in the 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. This contains all elements in the range [pair::first, pair::second).

As a 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 zero length and both iterators will point to the first element that is considered to go after the specified value.

Syntax

pair<iterator,iterator> 
  equal_range (const value_type& val) const;
pair<const_iterator,const_iterator> 
  equal_range (const value_type& val) const;
  
pair<iterator,iterator> 
  equal_range (const value_type& val);

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

Logarithmic i.e, Θ(log(n))

Example:

In the example below, the set::equal_range function returns the bounds of a range for specified value in MySet.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{10, 20, 30, 40, 50};
  set<int>::iterator it;

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

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

MySet contains: 10 20 30 40 50
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 set.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{10, 20, 30, 40, 50};
  set<int>::iterator it;

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

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

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

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

  return 0;
}

The output of the above code will be:

MySet contains: 10 20 30 40 50
MySet contains: 10 30 40 50

❮ C++ <set> Library