equal_range() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). equal_range() is a method in the STL that is used to find the sub-range within a given range where all the elements are equal to a given value.

Syntax:

equal_range ( iterator_begin, iterator_end, val );
equal_range ( iterator_begin, iterator_end, val, comparator );

Parameters: The equal_range() method accepts 4 parameters

  • iterator_begin: Iterator to the initial position
  • iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • val: Value to match
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: A pair object, whose first member (pair::first) is an iterator to the lower bound of the sub-range, and the second member (pair::second) its upper bound.
Note:
The respective values returned are the same as those returned by lower_bound() and upper_bound()

Example of equal_range() method

using namespace std;

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> v;
    v.push_back(10);
    v.push_back(8);
    v.push_back(20);
    v.push_back(30);
    v.push_back(30);
    v.push_back(30);
    v.push_back(30);
    v.push_back(50);

    for( vector<int>::iterator it = v.begin(); it != v.end() ; ++it)
    {
        cout<<*it<<"  ";
    }

    cout<<endl;

    pair< vector<int>::iterator, vector<int>::iterator > bound;
    bound = equal_range(v.begin(), v.end(), 30);
    cout<<"The element 30 is bounded from index "<< distance(v.begin(), bound.first) <<" to index "<< distance(v.begin(), bound.second);

}

Output:

The element 30 is bounded from index 3 to index 7

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top