I had almost the same problem, so I wrote this generic code (you might want to use a different namespace than std;)). The code below returns an iterator to the largest element in a sequence that is less than or equal to val. It uses O (N log N) time for N = std :: difference (first, last), assuming that O (1) is random access on [first ... last).
#include <iostream>
#include <vector>
#include <algorithm>
namespace std {
template<class RandomIt, class T>
RandomIt binary_locate(RandomIt first, RandomIt last, const T& val) {
if(val == *first) return first;
auto d = std::distance(first, last);
if(d==1) return first;
auto center = (first + (d/2));
if(val < *center) return binary_locate(first, center, val);
return binary_locate(center, last, val);
}
}
int main() {
std::vector<double> values = {0, 0.5, 1, 5, 7.5, 10, 12.5};
std::vector<double> tests = {0, 0.4, 0.5, 3, 7.5, 11.5, 12.5, 13};
for(double d : tests) {
auto it = std::binary_locate(values.begin(), values.end(), d);
std::cout << "found " << d << " right after index " << std::distance(values.begin(), it) << " which has value " << *it << std::endl;
}
return 0;
}
: http://ideone.com/X9RsFx
, std::vectors, std:: , . ( ) , val >= * [first, last) , std:: binary_search.
, .