Created
April 29, 2015 14:13
-
-
Save erikzenker/f228773a26639446c194 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
#include <iterator> | |
template<typename T> | |
struct Scan { | |
T value; | |
Scan(T init) : value(init){ | |
} | |
T operator()(const T &element){ | |
T prevValue = value; | |
value = value + element; | |
return prevValue; | |
} | |
}; | |
int main(){ | |
std::vector<int> input{{1,2,3,4,5}}; | |
std::transform(input.begin(), input.end(), std::ostream_iterator<int>(std::cout, " "), Scan<int>(0)); | |
return 0; | |
} |
A better and shorter solution with for_each and lambdas:
int value = 0;
std::for_each(input.begin(), input.end(), [&value](int &n){
int prevValue = value;
value += n;
n = prevValue;
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
std::transform does not guarantee in-order application of unary_op or binary_op. To apply a function to a sequence in-order or to apply a function that modifies the elements of a sequence, use std::for_each
source