fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <map>
  4. using namespace std;
  5.  
  6. template<typename Map, typename K>
  7. auto tolerant_find(const Map & map, const K & lookup, const K & tolerance) -> decltype(map.begin()) {
  8. // Assuming (first,last) is a sorted sequence of pairs
  9.  
  10. // First, find sub-sequence of keys "near" the lookup value
  11. auto first = map.lower_bound(lookup - tolerance);
  12. auto last = map.upper_bound(lookup + tolerance);
  13.  
  14. // If they are equal, the sequence is empty, and thus no entry was found.
  15. // Return the end iterator to be consistent with std::find.
  16. if (first == last) {
  17. return map.end();
  18. }
  19.  
  20. // Then, find the one with the minimum distance to the actual lookup value
  21. typedef typename Map::mapped_type T;
  22. return std::min_element(first, last, [lookup](std::pair<K,T> a, std::pair<K,T> b) {
  23. return std::abs(a.first - lookup) < std::abs(b.first - lookup);
  24. });
  25. }
  26.  
  27. int main() {
  28. std::map<float,int> mymap = {
  29. { 1.0, 1 },
  30. { 5.0, 2 },
  31. { 5.1, 3 },
  32. { 5.11, 4 },
  33. { 5.2, 5 }
  34. };
  35.  
  36. // This should find the key 5.11
  37. cout << tolerant_find(mymap, 5.15, 0.1)->first << endl;
  38. // This should find the key 5.2
  39. cout << tolerant_find(mymap, 5.16, 0.1)->first << endl;
  40.  
  41. // This should print "not found".
  42. cout << (tolerant_find(mymap, 2.0, 0.1) == mymap.end() ? "not found" : "found") << endl;
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
5.11
5.2
not found