fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iterator>
  5. #include <numeric>
  6. #include <cmath>
  7.  
  8. template<typename Iter>
  9. void show_max_difference(Iter beg, Iter end)
  10. {
  11. // calculate the absolute differences
  12. std::vector<double> diffs;
  13. std::adjacent_difference(beg, end, back_inserter(diffs), [](double x, double y){return std::abs(x-y);});
  14.  
  15. // find the largest one
  16. std::vector<double>::iterator it = std::max_element(diffs.begin()+1, diffs.end());
  17. size_t idx = std::distance(diffs.begin(), it);
  18. std::cout << "The largest difference is " << *it << " between " << beg[idx-1] << " and " << beg[idx] << '\n';
  19. }
  20. int main()
  21. {
  22. double a[9] = {1.93, -4.68, -5.05, -8.08, -2.95, -0.43, 7.03, -7.20, 9.86};
  23. show_max_difference(a, a+9);
  24. int a2[9] = {9, -4, -5, -8, -3, 0, 7, -7, 9};
  25. show_max_difference(a2, a2+9);
  26. }
  27.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
The largest difference is 17.06 between -7.2 and 9.86
The largest difference is 16 between -7 and 9