# C++ Algorithm Library - equal_range() Function

## Description

The C++ function std::algorithm::equal_range() returns a range of element that matches specific key. It uses binary comparison function 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, class Compare>
pair<ForwardIterator,ForwardIterator>
equal_range (ForwardIterator first, ForwardIterator last,const T& val, Compare comp);
```

## Parameters

• first − Forward iterator to the initial position.

• last − Forward iterator to the final position.

• val − Value to compare the elements.

• comp − A binary function which accepts two arguments and returns a bool.

## 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;

bool binary_pred(int a, int b) {
return (a > b);
}

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

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

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 3 times.
```
algorithm.htm