Search code examples
c++functiontemplatesfunctor

functor and function at priority_queue and sort of C++


I try to understand use of functor and function at C++

Please see the code below

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

bool mySort(int a, int b){
    if(a > b) return true;
    return false;
}

class myClass{

public:
    bool operator()(int a, int b){
        if(a>b) return true;
        return false;
    }
};

int main(){

    //(1) priority_queue<int, vector<int>, greater<int>> aa;
    //(2) priority_queue<int, vector<int>, greater<int>()> bb;
    //(3) priority_queue<int, vector<int>, myClass> cc;
    //(4) priority_queue<int, vector<int>, mySort> dd;

    vector<int> check={1,2,3,4,5,6,7};

    //(a) sort(check.begin(), check.end(), mySort);
    //(b) sort(check.begin(), check.end(), myClass);
    //(c) sort(check.begin(), check.end(), myClass());


    return 0;
}

I found only (1),(3) and (a),(c) works.

What is the difference between function and functor when using sort and priority_queue?

I know functor can maintain its state but, this information is not related in this case.

I also check sort and priority_queue but fail to understand it.

Could you help me?


Solution

  • When you instantiate a priority_queue, the third argument must be a type.
    greater<int> and myClass are types; greater<int>() and mySort are not.
    If you create a default priority_queue, it will default-initialise an ordering of the indicated type.

    priority_queue<int, vector<int>, greater<int>> aa;
    

    is equivalent to

    priority_queue<int, vector<int>, greater<int>> aa(greater<int>());
    

    and

    priority_queue<int, vector<int>, myClass> cc;
    

    is equivalent to

    priority_queue<int, vector<int>, myClass> cc(myClass());
    

    When you call sort, you give it a callable object as the third argument, and the template arguments are deduced from the function arguments.
    mySort and myClass() are callable objects; their types are bool(int,int) and myClass, respectively, and these types become the template arguments.
    myClass is a type and can't be used as a function argument.

    sort(check.begin(), check.end(), mySort);
    

    is equivalent to

    sort<vector<int>::iterator, bool(int,int)>(check.begin(), check.end(), mySort);
    

    and

    sort(check.begin(), check.end(), myClass());
    

    is equivalent to

    sort<vector<int>::iterator, myClass>(check.begin(), check.end(), myClass());