Reputation: 113
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<vector<int>> q;
q.push({1, 2, 3});
q.push({3});
q.push({1, 2});
q.push({0, 1, 2, 3, 4});
while (!q.empty()) {
cout << q.top().size() << endl;
q.pop();
}
}
The above code will output
1
3
2
5
I want to get
1
2
3
5
I searched around but not able to figure out the correct way or not sure it's possible. Any help will be great, thanks in advance.
Upvotes: 2
Views: 62
Reputation: 15009
Looking at the documentation, something like this might work:
// Using lambda to compare elements.
auto cmp = [](const std::vector<int> &left, const std::vector<int> &right)
{
return left.size() < right.size();
};
std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, decltype(cmp)> q(cmp);
Upvotes: 2
Reputation: 11311
While constructing priority_queue
, you can provide your own compare function.
Please see https://en.cppreference.com/w/cpp/container/priority_queue
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
Just change the types per your requirement
Upvotes: 2