fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. namespace std {
  6.  
  7. template<class RandomIt, class T>
  8. RandomIt binary_locate(RandomIt begin, RandomIt end, const T& val) {
  9. if(val == *end) return begin;
  10. auto d = std::distance(begin, end);
  11. if(d==1) return begin;
  12. auto center = (begin + (d/2));
  13. if(val < *center) return binary_locate(begin, center, val);
  14. return binary_locate(center, end, val);
  15. }
  16.  
  17. }
  18.  
  19. int main() {
  20. std::vector<double> values = {0, 0.5, 1, 5, 7.5, 10, 12.5};
  21. std::vector<double> tests = {0, 0.4, 0.5, 3, 7.5, 11.5, 12.5, 13};
  22. for(double d : tests) {
  23. auto it = std::binary_locate(values.begin(), values.end(), d);
  24. std::cout << "found " << d << " right after index " << std::distance(values.begin(), it) << " which has value " << *it << std::endl;
  25. }
  26. return 0;
  27. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
found 0 right after index 0 which has value 0
found 0.4 right after index 0 which has value 0
found 0.5 right after index 1 which has value 0.5
found 3 right after index 2 which has value 1
found 7.5 right after index 4 which has value 7.5
found 11.5 right after index 5 which has value 10
found 12.5 right after index 6 which has value 12.5
found 13 right after index 6 which has value 12.5