I am working on a problem. I have a number a
and a set of elements (say myset
). I want to find the number b
in myset
such that |ba|
is minimum. I am using it=upper_bound(a)
and then check |*it-a|
and |(*it-1)-a|
and take the minimum of these two. Is this the correct approach?
That's correct except for the edge cases: what if upper_bound
returns end()
and what if it returns begin()
?
// pre-conditions: contains at least 1 elem, is sorted
template <typename It, typename Value>
const Value& min_dist(It first, It last, const Value& a)
{
It it = std::upper_bound(first, last, a);
if (it == last) {
return *(std::prev(last, 1));
}
else if (it == first) {
return *it;
}
else {
// somewhere in the middle, so both it and prev are valid
It prev = std::prev(it, 1);
return (*it - a) < (a - *prev)
? *it : *prev;
}
}
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.