patterncppModerate
Code for sums in a vector
Viewed 0 times
codevectorforsums
Problem
I posted this code in an answer earlier today, but thought it was worth seeing if somebody could suggest further improvements:
Here I've placed fixed input into the vector
#include
#include
#include
#include
#include
template
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 inputs { 1, 2, 3, 4, 5, 10, 9, 8, 7, 6};
adjacent_sum(inputs.begin(), inputs.end(),
std::ostream_iterator(std::cout, "\t"));
std::cout (std::cout, "\t"),
std::plus());
}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.Solution
You make the assumption of random accesses iterators.
It would be nice to be able to do this with any iterator (including input iterator)
Now the following works:
It would be nice to be able to do this with any iterator (including input iterator)
template
OutIt adjacent_sum(InIt begin, InIt end, OutIt result)
{
if (begin == end)
{ return result; // From @Corbin
}
auto last = (*begin); // Get the value now before incrementing the iterator.
++begin;
while (begin != end)
{
auto next = (*begin);
*result = next + last;
last = next;
++result;
++begin;
}
return result;
}Now the following works:
adjacent_sum(std::istream_iterator(std::cin), std::istream_iterator(),
std::ostream_iterator(std::cout, "\t"));Code Snippets
template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result)
{
if (begin == end)
{ return result; // From @Corbin
}
auto last = (*begin); // Get the value now before incrementing the iterator.
++begin;
while (begin != end)
{
auto next = (*begin);
*result = next + last;
last = next;
++result;
++begin;
}
return result;
}adjacent_sum(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\t"));Context
StackExchange Code Review Q#54579, answer score: 12
Revisions (0)
No revisions yet.