Search code examples
c++arraysdata-structurespriority-queue

Make min priority queue of arrays c++


I want a min priority queue which instead of containing integers, stores arrays. The priority of each element is the first element in the array.

priority_queue<array<int, 6>, vector<int>, greater<int>> pq;
array<int, 6> arr = {a, b, c, d, e, f};
pq.push(arr);
array<int, 6> popArr = pq.pop();

When I do this I get the following error related to pushing:

no matching function for call to ‘std::priority_queue<std::array<int, 6>, std::vector<int>, std::greater<int> >::push(std::array<int, 6>&)’
 pq.push(arr);

And the following related to popping:

conversion from ‘void’ to non-scalar type ‘std::array<int, 6>’ requested
 array<int, 6> popArr = pq.pop();

How can I fix these errors?


Solution

  • First of all the type of data structure in priority queue is array<int,6>, so vector<int> should be written as vector<array<int,6>>.

    Now the third argument is comparator. So lets create a comparator :

    struct Compare{
        bool operator()(array<int,6> a,array<int,6> b){
        return a[0]>b[0];
    }
    };
    

    Now declaration looks like:

    priority_queue<array<int,6>, vector<array<int,6>, Compare > pq;
    

    Also, pq.pop() return type is void, So it should be pq.top() and then write pq.pop() to remove element from priority queue .