top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain how to use upper_bound() and lower_bound() in c++ using stl.

+1 vote
432 views

explained with code will be helpful.

posted May 24, 2016 by Rohit

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

upper_bound() returns an iterator to the elements in the given range which does not compare greater than the given value. The range given should be already sorted for upper_bound() to work properly. In other words it returns an iterator to the upper bound of the given element in the given sorted range and lower_bound() returns an iterator to the elements in the given range which does no compare less than the given value. The range given should be already sorted for lower_bound() to work properly. In other words it returns an iterator to the lower bound of the given element in the given sorted range.

        #include <iostream>     
        #include <algorithm>   
        #include <vector>
        using namespace std;

        int main ()
        {
          int input[] = {1,2,2,3,4,4,5,6,7,8,10,45};
          vector<int> v(input,input+12);

          vector<int>::iterator it1 ,it2,it3,it4;

          it1 = lower_bound(v.begin(), v.end(), 4); 
          /* points to fifth element in v */ 

          it2 = lower_bound (v.begin(), v.end(), 10);
          /* points to second last element in v */
          it3= upper_bound(v.begin(), v.end(), 6); 
      /* points to eight element in v */ 

      it4= upper_bound(v.begin(), v.end(), 4);
      /* points to seventh element in v */
   return 0;
        }
answer May 24, 2016 by Shivam Kumar Pandey
...