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