function template
<numeric>
std::adjacent_difference difference (1)template <class InputIterator, class OutputIterator> OutputIterator adjacent_difference (InputIterator first, InputIterator last, OutputIterator result);custom (2)
template <class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator adjacent_difference ( InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op );
Compute adjacent difference of range
Assigns to every element in the range starting at result the difference between its corresponding element in the range[first,last)
and the one preceding it (except for *result
, which is assigned *first
).
If x represents an element in [first,last)
and y represents an element in result
, the ys can be calculated as:
y0 = x0
y1 = x1 - x0
y2 = x2 - x1
y3 = x3 - x2
y4 = x4 - x3
... ... ...
The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class InputIterator, class OutputIterator>
OutputIterator adjacent_difference (InputIterator first, InputIterator last,
OutputIterator result)
{
if (first!=last) {
typename iterator_traits<InputIterator>::value_type val,prev;
*result = prev = *first;
while (++first!=last) {
val = *first;
*++result = val - prev; // or: *++result = binary_op(val,prev)
prev = val;
}
++result;
}
return result;
}
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
[first,last)
).
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
27
// adjacent_difference example
#include <iostream> // std::cout
#include <functional> // std::multiplies
#include <numeric> // std::adjacent_difference
int myop (int x, int y) {return x+y;}
int main () {
int val[] = {1,2,3,5,9,11,12};
int result[7];
std::adjacent_difference (val, val+7, result);
std::cout << "using default adjacent_difference: ";
for (int i=0; i<7; i++) std::cout << result[i] << ' ';
std::cout << '\n';
std::adjacent_difference (val, val+7, result, std::multiplies<int>());
std::cout << "using functional operation multiplies: ";
for (int i=0; i<7; i++) std::cout << result[i] << ' ';
std::cout << '\n';
std::adjacent_difference (val, val+7, result, myop);
std::cout << "using custom function: ";
for (int i=0; i<7; i++) std::cout << result[i] << ' ';
std::cout << '\n';
return 0;
}
using default adjacent_difference: 1 1 1 2 4 2 1 using functional operation multiplies: 1 2 6 15 45 99 132 using custom function: 1 3 5 8 14 20 23
[first1,last1)
are accessed (each element is accessed exactly once).
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