I'm trying to find the nearest value in an sorted array, but both upper_bound and lower_bound are giving the highest value.
float abc[] = {1,3,4,5,6,7,8,9};
float *a = lower_bound(abc, abc+8, 3.2);
cout<< *a;
return 0;
*a
will be 4 in both cases, as the value pointed to by a
would be 3.2
if that was inserted correctly into the container.
lower_bound
and upper_bound
will return the same iterator if the value passed is not present in the container, which is the case here.
The iterator returned by lower_bound
is defined to be the lowest position where the element passed could reside it was in the container, higher_bound
returns the highest position. They do not return anything related to the closest element present in the array.
In order to find the closest element, you know that the dereferenced result of lower_bound
is greater than or equal to the value passed. The value before that, if any, must be less. You can make use of this in order to arrive at the closest value.
As the value 3.2 is absent in the array then the both algorithms std::lower_bound
and std::upper_bound
will return the same iterator.
In such a case you should consider a previous iterator.
Here is a demonstrative program.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstdlib>
int main()
{
float abc[] = { 1, 3, 4, 5, 6, 7, 8, 9 };
float value = 3.2f;
auto it = std::lower_bound( std::begin( abc ), std::end( abc ), value );
auto closest = it;
if ( it == std::end( abc ) )
{
closest = std::prev( it );
}
else if ( it != std::begin( abc ) )
{
closest = std::min( std::prev( it ), it,
[&value]( const auto &p1, const auto &p2 )
{
return abs( value - *p1 ) < abs( value - *p2 );
} );
}
std::cout << *closest << " at position " << std::distance( std::begin( abc ), closest ) << std::endl;
return 0;
}
Its output is
3 at position 1
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.