fork(1) download
  1. #include <stdexcept>
  2. #include <iostream>
  3. #include <string>
  4. #include <map>
  5.  
  6. typedef std::map<std::string, double> map_type ;
  7.  
  8. const double smoothingFactor = .5 ;
  9.  
  10. double addDataPoint(map_type & m, map_type::value_type data)
  11. {
  12. map_type::iterator it = m.find(data.first) ;
  13.  
  14. if ( it == m.end() )
  15. {
  16. m[data.first] = data.second ;
  17. return data.second ;
  18. }
  19.  
  20. return it->second = smoothingFactor * data.second + (1-smoothingFactor) * it->second ;
  21. }
  22.  
  23. double getAverage(const map_type& m, const map_type::key_type & key )
  24. {
  25. map_type::const_iterator it = m.find(key) ;
  26. if ( it == m.end() )
  27. throw std::logic_error( "getAverage called for non-existent key: \"" + key + '"') ;
  28. return it->second ;
  29. }
  30.  
  31. std::ostream& operator<<(std::ostream& os, const map_type & map )
  32. {
  33. map_type::const_iterator it ;
  34. for ( it = map.begin(); it != map.end(); ++it )
  35. os << it->first << ": " << it->second << '\n' ;
  36. return os ;
  37. }
  38.  
  39. int main()
  40. {
  41. map_type emaMap ;
  42.  
  43. try
  44. {
  45. std::cout << "addDataPoint(\"a\", 4)\n" ;
  46. addDataPoint(emaMap, std::make_pair("a", 4)) ;
  47. std::cout << emaMap << '\n' ;
  48.  
  49. std::cout << "addDataPoint(\"b\", 8)\n" ;
  50. addDataPoint(emaMap, std::make_pair("b", 8)) ;
  51. std::cout << emaMap << '\n' ;
  52.  
  53. std::cout << "addDataPoint(\"a\", 6)\n" ;
  54. addDataPoint(emaMap, std::make_pair("a", 6)) ;
  55. std::cout << emaMap << '\n' ;
  56.  
  57. std::cout << "addDataPoint(\"b\", 12)\n" ;
  58. addDataPoint(emaMap, std::make_pair("b", 12)) ;
  59. std::cout << emaMap << '\n' ;
  60.  
  61. std::cout << "getAverage(\"a\")\n" ;
  62. std::cout << getAverage(emaMap, "a") << "\n\n" ;
  63.  
  64. std::cout << "getAverage(\"b\")\n" ;
  65. std::cout << getAverage(emaMap, "b") << "\n\n" ;
  66.  
  67. std::cout << "getAverage(\"c\")\n" ;
  68. std::cout << getAverage(emaMap, "c") << "\n\n" ;
  69. }
  70. catch (std::exception& ex)
  71. {
  72. std::cout << ex.what() << '\n' ;
  73. }
  74. }
  75.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
addDataPoint("a", 4)
a: 4

addDataPoint("b", 8)
a: 4
b: 8

addDataPoint("a", 6)
a: 5
b: 8

addDataPoint("b", 12)
a: 5
b: 10

getAverage("a")
5

getAverage("b")
10

getAverage("c")
getAverage called for non-existent key: "c"