Functors in Standard Library
I have been programming with the STL for a while now and I have a question about using functors. Look at this code
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct plus : public binary_function<int, int, int> {
int operator() (int x, int y) { return x + y; }
};
void my_print(int x) {
cout << x << endl;
}
int main(void)
{
vector<int> v(5);
vector<int> w(5);
vector<int> x(5);
fill(v.begin(),v.end(), 5);
fill(w.begin(),w.end(), 1);
transform(v.begin(),v.end(), w.begin(), x.begin(), ::plus());
for_each(x.begin(), x.end(), my_print);
return 0;
}
Note how I use :: plus which is an object that overrides () and then I use my_print which is a function. I understand that they both do the same thing (:: plus() calls overloaded () operator and my_print is a function pointer) I was wondering why the STL uses classes and inheritance (i.e. inheriting from binary_function<arg1,arg2, retval>). Is this so you can store more information in a function like member variables? Also, is there any difference in performance between the two ways I used STL functions?