equal_range [C++ Reference]
Keywords: stl,algorithm,equal_range
Date: 2009-10-09T01:52:55-0700

[[equal_range]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## equal_range

Syntax:

        #include <algorithm>
        pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val );
        pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val, CompFn comp );

The equal_range() function returns the range of elements between first and last that are equal to val. This function assumes that the elements between first and last are in order according to comp, if it is specified, or the < operator otherwise.

equal_range() can be thought of as a combination of the lower_bound and upper_bound functions, since the first of the pair of iterators that it returns is what lower_bound returns and the second iterator in the pair is what upper_bound returns.

For example, the following code uses equal_range() to determine all of the possible places that the number 8 can be inserted into an ordered vector of integers such that the existing ordering is preserved:

       vector<int> nums;
       nums.push_back( -242 );
       nums.push_back( -1 );
       nums.push_back( 0 );
       nums.push_back( 5 );
       nums.push_back( 8 );
       nums.push_back( 8 );
       nums.push_back( 11 );

       pair<vector<int>::iterator, vector<int>::iterator> result;
       int new_val = 8;

       result = equal_range( nums.begin(), nums.end(), new_val );

       cout << "The first place that " << new_val << " could be inserted is before "
            << *result.first << ", and the last place that it could be inserted is before "
            << *result.second << endl;

The above code produces the following output:

       The first place that 8 could be inserted is before 8,
       and the last place that it could be inserted is before 11

Related Topics: binary_search, lower_bound, upper_bound

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •