0

I wrote a code where I need to find lower_bound from square number sequence. But lower bound giving me result for upper_bound.

Here is my code & compiler link: http://cpp.sh/3cppb

// Example program
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
   std::vector<int> v{ 1, 4, 9, 16, 25 }; // all the square numbers
   
   int x = std::lower_bound(v.begin(), v.end(), 5) - v.begin() ;
   
   std:: cout<<"Postion "<<x<< "  value  "<<v[x] <<std::endl; //getting output for upperbound
   
}

Output:

Postion 2  value  9

Expected Output

Postion 1  value  4
Sayed Sohan
  • 1,385
  • 16
  • 23

3 Answers3

3

std::lower_bound returns the iterator to the first element which is greater or equal to the target value:

Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

As 9 is the first value which is greater or equal to 5 (it is greater, of course), the result is totally correct.

If you tried to find an element which is already in v, like 9, then you would get different results for std::lower_bound and std::upper_bound:

std::distance(begin(v), std::lower_bound(begin(v), end(v), 9)); // 2
std::distance(begin(v), std::upper_bound(begin(v), end(v), 9)); // 3
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
1

std::lower_bound is working correctly. The function returns the first element that is not less than the value provided. Since 9 is the first value that is not less than 5 you get that element.

std::upper_bound in this case will return the same element as it returns the first element greater than the specified value. Where you will see a difference is cases like

std::vector data = {4,4,4};
auto low = std::lower_bound(data.begin(), data.end(), 4);
auto high = std::upper_bound(data.begin(), data.end(), 4);

In this case low will be begin() as 4 is not less than 4 while high will be end() as there is no element greater than 4 in the vector.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

The quotation from the Standard, [lower.bound]:

template<class ForwardIterator, class T> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value);

Returns: The furthermost iterator i in the range [first,last] such that for every iterator j in the range [first,i) the following corresponding conditions hold: *j < value.

Evg
  • 25,259
  • 5
  • 41
  • 83