I wrote 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
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 (ie 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
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.
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 iteratorj
in the range[first,i)
the following corresponding conditions hold:*j < value
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.