I will show some more example with explanation. This functor is heavyly used in STL where
1) Many STL containers and algorithms require specifying a function to perform their operation.
2) A function that takes one parameter is called a unary function, whereas a function that takes two parameters is called a binary function.
3) STL defines three categories of functions.
1.1) Predicates- Trigger actions and always return true or false
1.2)Comparators-Order elements and always return true or false
1.3)General functions-Arbitrary operations on one or more arguments and often return a numeric value
Now we will discuss an example
#include
#include
#include
using namespace std;
class Greater_Than
{
private:
int limit;
public:
Greater_Than(int a) : limit(a) { }
bool operator()(int value)
{
return value > limit;
}
};
int main()
{
Greater_Than g(350);
vector
x.push_back(300);
x.push_back(460);
x.push_back(560);
x.push_back(660);
vector
p = find_if( x.begin(), x.end(), g );
if (p != x.end())
{
cout<< "Found element " << *p << endl;
}
}
Explanation.
The vector X is containing with 300,460,560,660.
when find_if() examines each item say x[j] in the vector x, the Greater_Than function object g will be called using operator() with the vector item
It is called like below.
// formally: g.operator()(x[j])
If it finds value greater than 350 , the very next value will be printed.
Sahu
No comments:
Post a Comment