Oto ogólny rozwiązanie wykorzystujące std::lower_bound
:
template <typename BidirectionalIterator, typename T>
BidirectionalIterator getClosest(BidirectionalIterator first,
BidirectionalIterator last,
const T & value)
{
BidirectionalIterator before = std::lower_bound(first, last, value);
if (before == first) return first;
if (before == last) return --last; // iterator must be bidirectional
BidirectionalIterator after = before;
--before;
return (*after - value) < (value - *before) ? after : before;
}
Zauważysz, że użyłem dwukierunkowych Iteratorów, co oznacza, że funkcja może działać tylko z iteratorami, które mogą być zarówno inkrementowane, jak i zmniejszane. Lepsza implementacja narzuciłaby jedynie koncepcję Input Iterators, ale dla tego problemu powinno to być wystarczająco dobre.
Ponieważ chcesz indeksu i nie iterator, można napisać niewiele funkcji pomocnika:
template <typename BidirectionalIterator, typename T>
std::size_t getClosestIndex(BidirectionalIterator first,
BidirectionalIterator last,
const T & value)
{
return std::distance(first, getClosest(first, last, value));
}
a teraz skończyć z kodu:
const int ARRAY_LENGTH = 5;
double myarray[ARRAY_LENGTH] = { 1.0, 1.2, 1.4. 1.5, 1.9 };
int getPositionOfLevel(double level)
{
return getClosestIndex(myarray, myarray + ARRAY_LENGTH, level);
}
co daje następujące wyniki:
level | index
0.1 | 0
1.4 | 2
1.6 | 3
1.8 | 4
2.0 | 4
możemy użyć "std :: min_element" z functorem, spójrz na mój przykład. – Rexxar
Prawie duplikat [tego postu] (http://stackoverflow.com/questions/469477/find-nearest-points-in-a-vector). – mwigdahl