Search code examples
c++priority-queue

Is possible to use container's size as priority_queue's priority in C++?


#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.


Solution

  • 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);