This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

function object, function pointer and function.


Hi, Everyone:

I compiled a short code that invovles function object and function pointer.

in the line: int count1 = count_if(v1.begin(), v1.end(), &lessThan20Function);

I used the funtion poiter to pass the address of function. It works very well,

However, when I deleted the symbol "&", it still works. "lessThan20Function" is the name of function. Can we use the function name as an argument?

What is the advantage of function object?

Thanks in advanace!

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

bool lessThan20Function(int value)
{
   return value < 20;
}

class LessThan20 {
public:
   bool operator() (int value) const
   {
       return value < 20;
   }
};

int main() {

   int iarr[10] = {2,4,55,6,66,10,22,14,70,1234};
   vector<int> v1(iarr, iarr+10);

   LessThan20 lt20;
   // count_if(start_iterator, end_iterator, predicate);

   // Pointer to a function as argument
   int count1 = count_if(v1.begin(), v1.end(), &lessThan20Function);
   cout << "There are " << count1 << " values less than 20" << endl;

   // Function object as argument
   int count2 = count_if(v1.begin(), v1.end(), lt20);
   cout << "There are " << count2 << " values less than 20" << endl;
   return 0;
]

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]