I posted this code in an answer earlier today, but thought it was worth seeing if somebody could suggest further improvements:
#include <numeric>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result) {
++begin;
while (begin != end) {
*result = *begin + *(begin-1);
++result;
++begin;
}
return result;
}
int main() {
std::vector<int> inputs { 1, 2, 3, 4, 5, 10, 9, 8, 7, 6};
adjacent_sum(inputs.begin(), inputs.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << "\n";
std::transform(inputs.begin(), inputs.begin()+inputs.size()/2,
inputs.rbegin(),
std::ostream_iterator<int>(std::cout, "\t"),
std::plus<int>());
}
Here I've placed fixed input into the vector inputs
. The intent is to first produce the sums of adjacent items in the input, and second produce the sum of the first item added to the last item, second item added to the second to last, and so on.
std::transform()
code misses the middle number on an odd-sized input. \$\endgroup\$