insert <int,pair<int,int>> priority_queue

554 Views Asked by At
priority_queue<pair<int,int>,int> maxh;

error:no default constructor exists for class "std::priority_queue<std::pair<int, int>, int, <error-type>>"

If i try this method

priority_queue<pair<int,int>,vector<pair<int,int>>,int> maxh;
    for (int i=0;i<n,i++){
        
        int x1 =  a[i][0]*a[i][0];
        int y1 =  a[i][1]*a[i][1]; 
        
         int sum = x1 + y1;
        maxh.push(sum,make_pair(a[i][0],a[i][1]));
    }

maxh.push(sum,make_pair(a[i][0],a[i][1])); gives the error

no instance of overloaded function "std::priority_queue<_Tp, _Sequence, _Compare>::push [with _Tp=std::pair<int, int>, _Sequence=std::vector<std::pair<int, int>, std::allocator<std::pair<int, int>>>, _Compare=int]" matches the argument list -- argument types are: (int, std::pair<int, int>) -- object type is: std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int>>>, int>
1

There are 1 best solutions below

2
On

OK I'm taking a guess here, because you haven't explained yourself.

I'm assuming that you want to put pairs onto your priority queue and order them using these formulae that are in your code

int x1 =  a[i][0]*a[i][0];
int y1 =  a[i][1]*a[i][1]; 
    
int sum = x1 + y1;

The simplest way to do that is to use a lambda function that compares two pairs using the formula above. Here's some sample code

#include <queue>
#include <utility>
using namespace std;

int main ()
{
    auto lambda = [](pair<int, int> x, pair<int, int> y){ 
        return x.first*x.first + x.second*x.second < 
               y.first*y.first + y.second*y.second; };
    priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(lambda)> maxh;
    int a[3][2] = { {1,2}, {2,2}, {1,0} };
    int n = 3;
    for (int i=0; i<n; i++) {
        maxh.push(make_pair(a[i][0],a[i][1]));
    }
    return 0;
}

The lambda function is in the first line auto lambda = ...;. I've assumed that you want largest first. If your want smallest first just change < to > in the lambda function.