Search code examples
c++c++11c++14heap

How to use make_heap to create a min heap in c++


How do I create a a min heap using the make_heap method in <algorithm>

From the documentation it says, we can pass in a third argument Compare comp that is a

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to be less than the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

So I tried passing in a function object as follows

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;

struct myComp {

    bool operator() (const pair<int, char>& lhs, const pair<int, char>& rhs) {
        return lhs.first > rhs.first;
    }
};

int main() {
    vector< pair<int, char> > Q;
    Q.push_back( pair<int, char>(10, 'c') );
    Q.push_back( pair<int, char>(123, 'a') );
    Q.push_back( pair<int, char>(2, 'd') );
    Q.push_back( pair<int, char>(9, 'f') );
    Q.push_back( pair<int, char>(81, 'b') );
    Q.push_back( pair<int, char>(4, 'e') );

    make_heap(Q.begin(), Q.end(), myComp);

    pop_heap(Q.begin(), Q.end());

    cout << Q.back().first << ", " << Q.back().second << endl;
    Q.pop_back();

    return 0;
}

and I am getting this following error

jdoodle.cpp: In function 'int main()':
jdoodle.cpp:25:38: error: expected primary-expression before ')' token
  make_heap(Q.begin(), Q.end(), myComp);
                                      ^

I don't really understand what this means, what am I doing wrong?


Solution

  • myComp is a type name, while std::make_heap is a function (template), and to call it you need to pass an object. So create an object of that type.

    make_heap(Q.begin(), Q.end(), myComp{});
    

    The {} will initialize the myComp object that you pass.

    When you read the documentation Compare is the deduced type of the functor, but note that the function template expects a comp function parameter, that's your object.