Created
December 27, 2014 16:38
-
-
Save why-jay/2604a4294a2e3456bb12 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// this is a functor | |
struct add_x { | |
add_x(int x) : x(x) {} | |
int operator()(int y) { return x + y; } | |
private: | |
int x; | |
}; | |
// Now you can use it like this: | |
add_x add42(42); // create an instance of the functor class | |
int i = add42(8); // and "call" it | |
assert(i == 50); // and it added 42 to its argument | |
std::vector<int> in; // assume this contains a bunch of values) | |
std::vector<int> out; | |
// Pass a functor to std::transform, which calls the functor on every element | |
// in the input sequence, and stores the result to the output sequence | |
std::transform(in.begin(), in.end(), out.begin(), add_x(1)); | |
assert(out[i] == in[i] + 1); // for all i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment