Search code examples
c++dictionarypriority-queuestd-pair

Problem with converting map to priority queue


Help me please, why it is not work?

I want to convert map<int, int> to priority queue of pairs, which which will be sorted by the second argument.

auto cmp = [](pair<int, int>& p1, pair<int, int>& p2) {return p1.second > p2.second;};

priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q;

map<int, int> m{{1,1}, {2,3}, {4,100}};

for (auto a : m)
    q_.push(a);

i want to get such a pq in descending order of priority {{4,100}, {2,3}, {1,1}}.


Solution

  • Change your code to this

    priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q(cmp);
    

    Lambda functions don't have default constructors (at least in some versions of C++) the true situation seems to be complicated. https://en.cppreference.com/w/cpp/language/lambda