Shubham Jain
Shubham Jain

Reputation: 1984

Why do we pass greater<string>() to the sort algorithm?

As I know, Functor is basically a class that overrides operator (). Now I will have to first instantiate a class, to use the override operator. For example -

class A {
    bool operator()(int a, int b) const {
        return a<b;
    }
}

Now when I want to pass this to sort function, I will first have to instantiate it.

A instance;
sort(a.begin(),a.end(),instance);

The above should be correct implementation as I am passing a function to sort function which it can use for comparison. Why do I have to pass instance() as argument instead of instance.

One more thing: when I pass something like greater(), I am not even instantiating the class!

Upvotes: 2

Views: 1574

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

std::greater is a functional object that is it is a structure that provides the function call operator.

Expression

std::greater<std::string>()

calls the constructor of the structure and creates a temporary object of type std::greater<std::string> for which the function call operator can be called in an algorithm.

Relative to your function object definition

class A {
    bool operator()(int a, int b) const {
        return a<b;
    }
}

to create an instance of the class you should use expression

A()

So you can write either

std::sort( a.begin(), a.end(), A() );

or

A instance;
std::sort( a.begin(), a.end(), instance );

Take into account that the results are equivalent for these code snippets

std::cout << A()( 10, 20 ) << std::endl;

and

A instance;

std::cout << instance( 10, 20 ) << std::endl;

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

Why do I have to pass instance() as argument instead of instance.

You don't.

Either pass instance (the name of the instance), or A() (which is a separate, temporary, instance).

One more thing , when I pass something like greater(), I am not even instantiating the class !

Sure you are. This is a temporary of type greater.


Don't forget to make your operator() be public.

Upvotes: 3

Related Questions