How to use the equal_range() function in C++
In this shot, we discuss how to use the equal_range() function in C++.
The equal_range() function is available in the < algorithm > library in C++ is used to return a range of elements that matches a specific key.
equal_range uses the operator < to compare. The elements from the range must be sorted in order.
Parameters
First: Forward iterator for the initial position of the derived range.Last: Forward iterator for the final position of the derived range.Value: Value for the comparison of the elements.
Forward iterators are iterators that can be used to access the sequence of elements in a range starting from the beginning towards its end.
Return value
equal_rangereturns a sub-range if an element is found.- If
valueis not equivalent to any element in the range, the sub-range returned has a length of zero, with both iterators pointing to the nearest value greater thanvalue(if any), or tolastifvalueis greater than all the elements in the range.
Code
Let’s look at the code snippet.
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){vector<int> vec = {4, 4, 5, 5, 5, 6, 7, 7, 7, 7, 7, 8, 9};int count = 0;auto range = equal_range(vec.begin(), vec.end(), 7);for (auto i = range.first; i!= range.second; ++i)++count;cout << "Element 7 occurs " << count << " times." << endl;return 0;}
Explanation
-
In lines 1 to 3, we import the required header files.
-
In line 5, we make a
mainfunction. -
In line 7, we initialize a
vectorofintdata type. -
In line 8, we declare a variable of
intdata type. -
In line 10, we use the
equal_range()function to find the sub-range of element 7. -
In line 12, we use a loop to count the elements in the sub-range to provide the result.
-
In line 14, we display the number of elements in the sub-range with a message.
In this way, we can use the equal_range() function in C++.