Skip to main content
3 of 4
edited body
Snowhawk
  • 6.4k
  • 1
  • 18
  • 36

I would just use adjacent_difference in the numeric library. It's designed to accept custom binary ops such as plus<> and multiplies<> from the functional library.

std::adjacent_difference(inputs.begin(), inputs.end(), std::ostream_iterator<int>(std::cout, " "), std::plus<int>());

If you are going to use your own adjacent sum, please include handling for empty/single element lists.

template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result) {
    if (begin == end)    // Corbin
        return result;

    auto last = *begin;  // Loki
    for (*result = last; ++begin != end;) { // Me
        auto next = *begin;
        *++result = last + next;
        last = std::move(next);
    }

    return result;
}
Snowhawk
  • 6.4k
  • 1
  • 18
  • 36