fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. template<class T>
  7. struct PredRetainMax;
  8.  
  9. template<class Time, class Val>
  10. struct PredRetainMax<std::pair<Time, Val>>
  11. {
  12. PredRetainMax(Time cutoff, Val& m) :_cutoff(cutoff), _max(m) {}
  13. bool operator()(const std::pair<Time, Val>& s)
  14. {
  15. //if older than cutoff, remove
  16. if (s.first < _cutoff) return true;
  17. //otherwise, keep and update max
  18. _max = std::max(_max, s.second);
  19. return false;
  20. }
  21. Val get() { return _max; }
  22. private:
  23. Time _cutoff;
  24. Val& _max;
  25. };
  26.  
  27. std::ostream& operator<<(std::ostream& ostr, const std::list<std::pair<unsigned, double>>& list)
  28. {
  29. for (auto &i : list) {
  30. ostr << "<" << i.first << "," << i.second << "> ";
  31. }
  32. return ostr;
  33. }
  34.  
  35. int main()
  36. {
  37. using sample = std::pair<unsigned, double>;
  38. using pred = PredRetainMax<sample>;
  39.  
  40. sample a{ 1,12.2 };
  41. sample b{ 2,11.778 };
  42. sample c{ 3,9.2 };
  43. sample d{ 4,-2.6 };
  44. sample e{ 5,10.1 };
  45.  
  46. std::list<sample> samples{ d,c,b,a };
  47. cout << "original list is: " << samples << endl << endl;
  48.  
  49. double maxval(-std::numeric_limits<double>::infinity());
  50. //eliminate samples older than 2
  51. samples.remove_if(pred(2, maxval));
  52. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  53.  
  54. //add new value
  55. samples.push_front(e);
  56. //reset max
  57. maxval = -std::numeric_limits<double>::infinity();
  58. //eliminate samples older than 2
  59. samples.remove_if(pred(2, maxval));
  60. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  61.  
  62. //reset max
  63. maxval = -std::numeric_limits<double>::infinity();
  64. //eliminate samples older than 3
  65. samples.remove_if(pred(3, maxval));
  66. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
original list is: <4,-2.6> <3,9.2> <2,11.778> <1,12.2> 

max is: 11.778, list is: <4,-2.6> <3,9.2> <2,11.778> 

max is: 11.778, list is: <5,10.1> <4,-2.6> <3,9.2> <2,11.778> 

max is: 10.1, list is: <5,10.1> <4,-2.6> <3,9.2>