Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Numeric::adjacent_difference() function



The C++ std::numeric::adjacent_difference() function is used to return the difference between consecutive elements in a range and stores the result in another range, starting from the first element. The first element is copied directly to the output, while the subsequent element is the result of subtracting the previous element with the current one.

Syntax

Following is the syntax for std::numeric::adjacent_difference() function.

adjacent_difference (InputIterator first, InputIterator last, OutputIterator result);
or
adjacent_difference ( InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op );

Parameters

  • first, last − It indicate the iterators to the initial and final positions in a sequence.
  • init − It is an initial value for the accumulator.
  • binary_op − It is binary operation.

Return Value

It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored.

Exceptions

It throws if any of binary_op, the assignments or an operation on an iterator throws.

Data races

The elements in the range [first1,last1) are accessed.

Example 1

In the following example, we are going to consider the basic usage of the adjacent_difference() function.

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > x = {11,23,12,32};
   std::vector < int > y(x.size());
   std::adjacent_difference(x.begin(), x.end(), y.begin());
   for (int n: y) {
      std::cout << n << " ";
   }
   return 0;
}

Output

Output of the above code is as follows −

11 12 -11 20

Example 2

Consider the following exaple, where we are going to use the custom binary operation.

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a = {2,31,2,3,4};
   std::vector < int > b(a.size());
   std::adjacent_difference(a.begin(), a.end(), b.begin(), std::multiplies < int > ());
   for (int n: b) {
      std::cout << n << " ";
   }
   return 0;
}

Output

Following is the output of the above code −

2 62 62 6 12
numeric.htm
Advertisements