Skip to content

Instantly share code, notes, and snippets.

@erikzenker
Created April 29, 2015 14:13
Show Gist options
  • Save erikzenker/f228773a26639446c194 to your computer and use it in GitHub Desktop.
Save erikzenker/f228773a26639446c194 to your computer and use it in GitHub Desktop.
#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;
}
@erikzenker
Copy link
Author

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