C++ Algorithm Library - equal_range() Function


The C++ function std::algorithm::equal_range() returns a range of element that matches specific key. It uses operator< for comparison. The element from the range must be in sorted order.


Following is the declaration for std::algorithm::equal_range() function form std::algorithm header.


template <class ForwardIterator, class T>
equal_range (ForwardIterator first, ForwardIterator last, const T& val);


  • first − Forward iterator to the initial position.

  • last − Forward iterator to the final position.

  • val − value to compare the elements.

Return value

Returns a subrange if element founds. If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both iterators pointing to the nearest value greater than val, if any, or to last, if val compares greater than all the elements in the range.


Throws exception if either element comparison or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Approximately 2*log2(n)+1 element.


The following example shows the usage of std::algorithm::equal_range() function.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 2, 2, 2};
   int cnt = 0;

   auto range = equal_range(v.begin(), v.end(), 2);

   for (auto it = range.first; it != range.second; ++it)
   cout << "Element 2 occurs " << cnt << " times." << endl;

   return 0;

Let us compile and run the above program, this will produce the following result −

Element 2 occurs 4 times.
Kickstart Your Career

Get certified by completing the course

Get Started