Created
January 19, 2014 04:47
-
-
Save ducalpha/8500579 to your computer and use it in GitHub Desktop.
functor example
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
// Source: http://stackoverflow.com/questions/356950/c-functors-and-their-uses | |
#include <assert.h> | |
#include <vector> | |
#include <algorithm> | |
#include <iostream> | |
struct add_x { | |
add_x(int x) : x(x) {} | |
int operator()(int y) {return x+y;} | |
private: int x; | |
}; | |
int main() | |
{ | |
add_x add1(1); | |
int i = add1(1); | |
assert(i == 2); | |
int myints[] = {1, 2, 3, 4, 5}; | |
std::vector<int> in(myints, myints + sizeof(myints) / sizeof(int)); | |
std::vector<int> out (in); | |
std::transform(in.begin(), in.end(), out.begin(), add_x(10)); | |
for (int i = 0; i < in.size(); ++i) { | |
//assert(out[i] == in[i] + 1); | |
std::cout << out.at(i) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment