Get both the lower and upper bound insertion points for a sorted sequence using algorithm equal_range - C++ STL Algorithm

C++ examples for STL Algorithm:equal_range

Description

Get both the lower and upper bound insertion points for a sorted sequence using algorithm equal_range

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <vector> // vector class-template definition 
#include <iterator> // ostream_iterator 
using namespace std; 

int main() /*from  w ww . ja  v  a2s.  c o  m*/
{ 
   const int SIZE = 10; 
   int a1[ SIZE ] = { 2, 2, 4, 4, 4, 6, 6, 6, 6, 8 }; 
   vector< int > v( a1, a1 + SIZE ); // copy of a1 
   ostream_iterator< int > output( cout, " " ); 

   cout << "Vector v contains:\n" ; 
   copy( v.begin(), v.end(), output ); 

   // use equal_range to determine both the lower- and 
   // upper-bound insertion points for 6 
   pair< vector< int >::iterator, vector< int >::iterator > eq; 
   eq = equal_range( v.begin(), v.end(), 6 ); 
   cout << "\nUsing equal_range:\n          Lower bound of 6 is element " 
         << ( eq.first - v.begin() ) << " of vector v" ; 
   cout << "\n      Upper bound of 6 is element " 
       << ( eq.second - v.begin() ) << " of vector v" ; 
   cout << "\n\nUse lower_bound to locate the first point\n" 
       << "at which 5 can be inserted in order"; 

    // use equal_range to determine both the lower- and 
    // upper-bound insertion points for 5 
    eq = equal_range( v.begin(), v.end(), 5 ); 
    cout << "\n      Lower bound of 5 is element " 
       << ( eq.first - v.begin() ) << " of vector v"; 
    cout << "\n      Upper bound of 5 is element " 
       << ( eq.second - v.begin() ) << " of vector v" << endl; 
}

Result


Related Tutorials