C++ Algorithm Library - equal_range() Function


Advertisements

Description

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.

Declaration

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

C++98

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

Parameters

  • 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.

Exceptions

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.

Example

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)
      ++cnt;
	
   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.
algorithm.htm
Advertisements