यहाँ 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
स्रोत
2009-03-31 14:09:17
हम उपयोग कर सकते हैं एक functor के साथ "std :: min_element", मेरा उदाहरण देखें। – Rexxar
बहुत अधिक [इस पोस्ट] का एक डुप्लिकेट (http://stackoverflow.com/questions/469477/find-nearest-points-in-a-vector)। – mwigdahl