fork download
  1. #include <iostream>
  2. #include <set>
  3.  
  4. // works on both `const` and non-`const` associative containers:
  5. template<class Container>
  6. auto my_equal_range( Container&& container, double target, double epsilon = 0.00001 )
  7. -> decltype( container.equal_range(target) )
  8. {
  9. auto lower = container.lower_bound( target-epsilon );
  10. auto upper = container.upper_bound( target+epsilon );
  11. return std::make_pair(lower, upper);
  12. }
  13.  
  14. template<typename Container>
  15. bool orig_key_exists( Container const& container, double target, double epsilon = 0.00001 ) {
  16. auto range = my_equal_range(container, target, epsilon);
  17. return range.first == range.second;
  18. }
  19.  
  20. template<typename Container>
  21. bool proposed_key_exists( Container const& container, double target, double epsilon = 0.00001 ) {
  22. auto range = my_equal_range(container, target, epsilon);
  23. return range.first != range.second;
  24. }
  25.  
  26. void test(const std::set<double>& s, double target, bool expected_exists)
  27. {
  28. bool proposed = orig_key_exists(s, target);
  29. std::cout << "original test for key " << target << ": " << (orig_key_exists(s, target) == expected_exists ? "PASS" : "FAIL") << std::endl;
  30. std::cout << "proposed test for key " << target << ": " << (proposed_key_exists(s, target) == expected_exists ? "PASS" : "FAIL") << std::endl;
  31. std::cout << std::endl;
  32. }
  33.  
  34. int main() {
  35. std::set<double> s = {1, 2, 3};
  36.  
  37. test(s, 2, true);
  38. test(s, 100, false);
  39. test(s, -5, false);
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
original test for key 2: FAIL
proposed test for key 2: PASS

original test for key 100: FAIL
proposed test for key 100: PASS

original test for key -5: FAIL
proposed test for key -5: PASS