fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <unordered_set>
  4. #include <chrono>
  5.  
  6. struct EqualPred
  7. {
  8. constexpr bool operator()(const double& lhs, const double& rhs) const
  9. {
  10. if (std::isnan(lhs) && std::isnan(rhs)) return true;
  11. return lhs == rhs;
  12. }
  13. };
  14.  
  15. template <typename T>
  16. struct Hash
  17. {
  18. size_t operator()(const T& value) const
  19. {
  20. return std::hash<T>()( std::isnan(value) ? NAN : value);
  21. }
  22.  
  23.  
  24. };
  25.  
  26. std::unordered_set<double, Hash<double>, EqualPred> s;
  27.  
  28. constexpr int N=5000;
  29. void test_insert(double value)
  30. {
  31.  
  32. auto begin = std::chrono::high_resolution_clock::now();
  33. for (int i = 0; i < N; i++) {
  34. s.insert(value);
  35. }
  36. auto end = std::chrono::high_resolution_clock::now();
  37. std::cout << "Duration: " << (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() / 1e9) << "\n";
  38. std::cout << "Number of elements: "<<s.size()<<"\n";
  39. }
  40.  
  41. int main(){
  42. std::cout << "Not NAN\n";
  43. test_insert(1.0); //takes 0.0001 s
  44. std::cout << "NAN\n";
  45. test_insert(NAN);
  46. test_insert(-NAN);
  47.  
  48. std::cout << s.size() << std::endl;
  49. //takes 0.2 s
  50. }
Success #stdin #stdout 0s 4264KB
stdin
Standard input is empty
stdout
Not NAN
Duration: 0.000180664
Number of elements: 1
NAN
Duration: 0.000192384
Number of elements: 2
Duration: 0.000154591
Number of elements: 2
2