adjacent_difference

Syntax:

    #include <numeric>
    output_iterator adjacent_difference( input_iterator start, input_iterator end, output_iterator result );
    output_iterator adjacent_difference( input_iterator start, input_iterator end, output_iterator result, BinaryFunction f );

The adjacent_difference() function calculates the differences between adjacent elements in the range [start,end) and stores the result starting at result. (Specifically, the element at start will be copied to result; and then the difference between the element at start + i and start + (i-1) will be stored at result + i.)

If a binary function f is given, it is used instead of the - operator to compute the differences. adjacent_difference() runs in linear time.

Following example displays the differences between adjacent elements in a vector.

 #include <algorithm>
 #include <iostream>
 #include <iterator>
 #include <numeric>
 #include <vector>
 
 int main()
 {
   std::vector<int> v;
   for (int i = 3; i <= 10; ++i)
     v.push_back(i);
 
   // display elements of v
   std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
 
   std::cout << std::endl;
 
   // display all differences between elements
   std::adjacent_difference(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
 
   return 0;
 }

When run, this code displays the following output:

 3 4 5 6 7 8 9 10
 3 1 1 1 1 1 1 1

Related Topics: accumulate, count, inner_product, partial_sum