这是使用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;
}
您会注意到我使用了双向迭代器,这意味着该函数只能与可以递增和递减的迭代器一起使用。更好的实现只会强加输入迭代器的概念,但对于这个问题,这应该足够了。
既然你想要索引而不是迭代器,你可以写一个小辅助函数:
template <typename BidirectionalIterator, typename T>
std::size_t getClosestIndex(BidirectionalIterator first,
BidirectionalIterator last,
const T & value)
{
return std::distance(first, getClosest(first, last, value));
}
现在你会得到这样的代码:
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);
}
给出以下结果:
level | index
0.1 | 0
1.4 | 2
1.6 | 3
1.8 | 4
2.0 | 4