The documentation for std::adjacent_difference
says that the first element written to the output is the first element of the input, unchanged. For my use case, I want to remove this first element. My question is, what is the most readable way to do this that is also maximally efficient?
For example, given [1, 3, 7]
, std::adjacent_difference
will give [1, 2, 4]
but that first element isn't actually a difference, it is just the first 1 we already had.
Currently, I have copied the reference implementation and modified it to not write the first element, and to perform the write in the loop before incrementing the output iterator instead of after:
template<class InputIt, class OutputIt>
constexpr
OutputIt adjacent_difference(InputIt first, InputIt last,
OutputIt d_first)
{
if (first == last) return d_first;
typedef typename std::iterator_traits<InputIt>::value_type value_t;
value_t acc = *first;
while (++first != last) {
value_t val = *first;
*d_first++ = val - std::move(acc); // <-- previously *++d_first = ...
acc = std::move(val);
}
return d_first;
}
This works, but of course isn't very satisfying since it copies over code from an existing algorithm. Is it possible to make an inserter that ignores the first write and increment? What performance cost would that incur?
question from:
https://stackoverflow.com/questions/65883787/how-can-i-modify-stdadjacent-difference-to-only-give-the-diffs 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…