fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. using sample = std::pair<unsigned, double>;
  7.  
  8. std::ostream& operator<<(std::ostream& ostr, const std::list<sample>& list)
  9. {
  10. for (auto &i : list) {
  11. ostr << "<" << i.first << "," << i.second << "> "; }
  12. return ostr;
  13. }
  14.  
  15. int main() {
  16.  
  17. sample a{ 1,12.2 };
  18. sample b{ 2,11.778 };
  19. sample c{ 3,9.2 };
  20. sample d{ 4,-2.6 };
  21. sample e{ 5,10.1 };
  22.  
  23. std::list<sample> samples{ d,c,b,a };
  24. cout << "list is: " << samples << endl << endl;
  25.  
  26. double maxval = -std::numeric_limits<double>::infinity();
  27. unsigned cutoff = 2;
  28. samples.remove_if([&maxval,cutoff](sample s)
  29. {
  30. //if older than cutoff, remove
  31. if (s.first < cutoff) return true;
  32. //otherwise, keep and update max
  33. maxval = std::max(maxval, s.second);
  34. return false;
  35. });
  36. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  37.  
  38. samples.push_front(e);
  39. maxval = -std::numeric_limits<double>::infinity();
  40. samples.remove_if([&maxval, cutoff](sample s)
  41. {
  42. if (s.first < cutoff) return true;
  43. maxval = std::max(maxval, s.second);
  44. return false;
  45. });
  46. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  47.  
  48. maxval = -std::numeric_limits<double>::infinity();
  49. cutoff = 3;
  50. samples.remove_if([&maxval,cutoff](sample s)
  51. {
  52. if (s.first < cutoff) return true;
  53. maxval = std::max(maxval, s.second);
  54. return false;
  55. });
  56. cout << "max is: " << maxval << ", list is: " << samples << endl << endl;
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
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>