fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace::std;
  6.  
  7. int nearest(vector<int> a, int x)
  8. {
  9. auto r = equal_range(a.begin(), a.end(), x);
  10. if (r.first == a.begin()) return a[0];
  11. if (r.first == a.end()) return a[a.size() - 1];
  12. return x - r.first[-1] <= r.first[0] - x ? r.first[-1] : r.first[0];
  13. }
  14.  
  15. int main(void)
  16. {
  17. vector<int> a = {98, 100, 198, 200, 250, 298};
  18.  
  19. cout << 50 << " -> " << nearest(a, 50) << endl;
  20. cout << 195 << " -> " << nearest(a, 195) << endl;
  21.  
  22. return 0;
  23. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
50 -> 98
195 -> 198