Created
November 16, 2012 13:28
-
-
Save stephenLee/4087363 to your computer and use it in GitHub Desktop.
Functors(Function objects) demo
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
| // A functor is any object that can be used with () in the manner of a function. | |
| // includes pointers to functions, and class objects for which the () operator (function call operator) is overloaded | |
| #include <iostream> | |
| #include <vector> | |
| #include <algorithm> | |
| using namespace std; | |
| class Print { | |
| public: | |
| void operator() (int elem) const { | |
| cout << elem << " "; | |
| } | |
| }; | |
| int main() { | |
| vector<int> vect; | |
| for (int i = 1; i < 10; i++) { | |
| vect.push_back(i); | |
| } | |
| Print print_it; | |
| for_each(vect.begin(), vect.end(), print_it); | |
| cout << endl; | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment