std::upper_bound and std::lower_bound for Vector in C++ STL

Click here for Set 1 and Set 2 of Vectors.
 

Vector – upper_bound and lower_bound

 
Iterator lower_bound (Iterator first, Iterator last, const val)
Iterator upper_bound (Iterator first, Iterator last, const val)
 
lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than ‘val’.
 
upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘val’.
 
 

filter_none

edit
close

play_arrow

link
brightness_4
code

// lower_bound and upper_bound in vector
#include <iostream>
#include <algorithm>    // for lower_bound, upper_bound and sort
#include <vector>       // for vector
  
using namespace std;
  
int main ()
{
    int gfg[] = {5,6,7,7,6,5,5,6};
      
    vector<int> v(gfg,gfg+8);    // 5 6 7 7 6 5 5 6
  
    sort (v.begin(), v.end());  // 5 5 5 6 6 6 7 7
  
    vector<int>::iterator lower,upper;
    lower = lower_bound (v.begin(), v.end(), 6); 
    upper = upper_bound (v.begin(), v.end(), 6); 
  
    cout << "lower_bound for 6 at position " << (lower- v.begin()) << '\n';
    cout << "upper_bound for 6 at position " << (upper - v.begin()) << '\n';
  
    return 0;
}

chevron_right


 
Output :

lower_bound for 6 at position 3
upper_bound for 6 at position 6

 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up