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.
SyntaxFollowing 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
It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored.
ExceptionsIt throws if any of binary_op, the assignments or an operation on an iterator throws.
Data racesThe elements in the range [first1,last1) are accessed.
Example 1In 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 20Example 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4