use greater<char>() in priority_queue

Viewed 126
#include <iostream>
#include <iterator>
#include <queue>

using namespace std;

int main()
{
    vector<char> a(256);
    copy(istream_iterator<char>{ cin }, istream_iterator<char>{}, begin(a));
    priority_queue<char> q{ less<char> (),a }; // less -> greater = compile error
    while (!q.empty()) {
        cout << q.top();
        q.pop();
    }

}

I'm trying to practice priority_queue. and I can't use greater<char>() intead of less Why I can't?

1 Answers

The problem is, given priority_queue<char> q ..., the compare type would be the default template argument, i.e. std::less<char>, which doesn't match if you pass greater<char> as constructor argument.

You can specify all the template arguments explicitly as

priority_queue<char, vector<char>, greater<char>> q{ greater<char> (),a };

Or don't specify any template arguments to take advantage of class template argument deduction (since C++17).

priority_queue q{ greater<char> (),a };
Related