close

consider the following function:

int foo();

The function name , foo , is actually a constant pointer.

When a function is called (via the () operator), the function pointer is dereferenced (* operator)

and execution branches to the function.

So the function pointer is a method which we use function like a object.

The technique , function object , always use in STL algorithm as follow example.

we can use function name , or use class with operator() as a function object.


#include <iostream> 
#include <algorithm> 
#include <vector> 
using namespace std; 
bool myfunction (int i,int j) { return (i<j); } 
struct myclass 
bool operator() (int i,int j) return (i<j);} 
} myobject; 
int main () 
int myints[] = {32,71,12,45,26,80,53,33}; 
vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33 
vector<int>::iterator it; 
// using default comparison (operator <): 
sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33 
// using function as comp , myfunction is a constant pointer here!!
sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80) 
// using object as comp 
sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80) 
// print out content: 
cout << "myvector contains:";
 for (it=myvector.begin(); it!=myvector.end(); ++it) 
cout << " " << *it; cout << endl; 
return 0; 
}




ref : http://www.cplusplus.com/reference/algorithm/sort/

ref : http://www.learncpp.com/cpp-tutorial/78-function-pointers/

ref : http://kheresy.wordpress.com/2010/11/09/function_object/

arrow
arrow
    全站熱搜

    JerryCheng 發表在 痞客邦 留言(0) 人氣()