Calculate adjacent differences elements C++
The adjacent_difference() calculate differences between range of elements [first,last) in a container. The result is a sequence in which the first element is corresponding to the first element of the sequence being processed, and the remaining elements are corresponding to the calculated differences between adjacent elements.
Syntax: adjacent_difference (first, last, result );
#include <iostream> #include <vector> #include <numeric> using namespace std; int main(){ int i; vector vec1(10), vec2(10); //insert elements vec1[1] = 2; vec1[2] = 5; vec1[3] = 7; vec1[4] = 15; vec1[5] = 19; vec1[6] = 24; cout << "Default values: "; for(i=0; i<7; i++) cout << vec1[i] << " "; cout << endl; cout << "calculating the adjacent difference... "< //adjacent_difference(first,last,results) adjacent_difference(vec1.begin(), vec1.end(), vec2.begin()); cout << "The adjacent_difference is: "; for(i=0; i<7; i++) cout << vec2[i] << " "; cout<< endl; return 0; }//end of main
program output
Default values: 0 2 5 7 15 19 24 calculating the adjacent difference... The adjacent difference is: 0 2 3 2 8 4