I have seen many articles here but still haven't figured out the advantage of a functor class over a simple function in the case of comparison. So I have a code excerpt in which they want to sort a vector of unsigned char *
by simply going through each character and comparing the ASCII code with priority from left to right.
The functor is
class Sorter {
private:
unsigned int length;
public:
Sorter( unsigned int _length ): length( _length ) {}
bool operator()( const unsigned char* keyl, const unsigned char* keyr ) { return cmpKey( keyl, keyr, length ); }
};
and the cmpKey()
function basically does what I described above. The call to sort the data is
sort( localList.begin(), localList.end(), Sorter( 100 ) );
where 100 is the length of each string. So, I have read that the functor has the advantage of storing the stage from call to call and allows the class to be used as an ordinary function. I have two questions:
What is the advantage of this in this case?
How many instances of Sorter
class will be created? Is it only 1 or as many as the elements of locaList
?
The primary use of functors is to create functions at runtime that possess some state. This is important in scenarios where you need a function to possess some information, but you cannot pass this information into the function as a parameter. One common example of this is in algorithms like std::sort
where the comparator function must take only two arguments (the things to compare) so you cannot just pass in extra information as parameters. You must instead create a function object at runtime and pass in that information in the constructor.
This is essentially what you do when you call
sort( localList.begin(), localList.end(), Sorter( 100 ) );
You are creating a Sorter function wherein you pass the information about the 100 when constructing the function. Calling it still requires only two parameters so this will work in the std::sort
algorithm. There is no way to do this with regular functions, besides things like std::bind
.