Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::adjacent_difference: differences between neighbors

std::adjacent_difference writes the first element and then applies an operation to each current and previous element. It returns the iterator past the final output.

Version: C++23

Syntax

template<class InputIt, class OutputIt>
constexpr OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt d_first);

template<class InputIt, class OutputIt, class BinaryOperation>
constexpr OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt d_first, BinaryOperation op);

std::adjacent_difference from <numeric> transforms [first, last) into output at d_first. For nonempty input, the first result copies the first element; later results are current - previous or binary_op(current, previous).

For {2, 5, 9}, the default operation produces {2, 3, 4}. An empty range writes nothing and returns d_first. The destination must hold as many elements as the input.

The custom operation receives the current element first and the previous element second. It must not modify the input or invalidate iterators. d_first == first is permitted by the overload without an execution policy. With an execution-policy overload, the input and output ranges must not overlap.

Examples

#include <array>
#include <iostream>
#include <numeric>

int main() {
    const std::array input{2, 5, 9};
    std::array<int, 3> output{};
    std::adjacent_difference(input.begin(), input.end(), output.begin());
    std::cout << output[0] << ' ' << output[1] << ' ' << output[2] << '\n';
}

Result

2 3 4

std::adjacent_difference → 2 3 4

Sources