Comparator function not working as I wanted (in ascending order) in priority queue C++

Viewed 37

I was working on LeetCode#973, my approach was to initialize a priority queue with data field as a pair of Int & a nested pair of two Int.

Example:

priority_queue< pair< float, pair< int, int > > >

Nested pair DS of <INT, INT>will store 2-D coordinates and FLOAT will store the distance calculated from the coordinate ( 0, 0 ).

I have created a comparator function that will return k no. of data from the priority queue in ascending order, but it is not working on this data set : [[2,10],[-9,-9],[0,8],[-2,-2],[8,9],[-10,-7],[-5,2],[-4,-9]]

The Answer should be [[-2,-2],[-5,2],[0,8],[-4,-9],[2,10],[8,9],[-10,-7]]

But I'm getting this [[8,9],[-9,-9],[2,10],[-4,-9],[0,8],[-5,2],[-2,-2]], Instead of getting (-10, -7) in the result array, I'm getting (-9, -9).

This is my code with output in VS Code.

This is the code :

#include<bits/stdc++.h>

using namespace std;


class cmp {
public:
        bool operator()(pair<float,pair<int,int>> a, pair<int,pair<int,int>> b)    {
        return a.first > b.first;
    }
};
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
    vector<vector<int>> result(k);
    priority_queue<pair<float,pair<int,int>>, vector<pair<float,pair<int,int>>>,cmp> hash;
    for(auto i : points)    {
        float distance = sqrt(pow(i[0],2) + pow(i[1],2));
        hash.push(make_pair(distance,make_pair(i[0],i[1])));
    }
    while(k)  {
        result[k - 1].push_back(hash.top().second.first);
        result[k - 1].push_back(hash.top().second.second);
        hash.pop();
        --k;
    }
    return result;
}

int main()
{
    vector<vector<int>> a({{2,10},{-9,-9},{0,8},{-2,-2},{8,9},{-10,-7},{-5,2},{-4,-9}});
    vector<vector<int>> b = kClosest(a,7);
    for(auto i : b)
    cout<<"["<<i[0]<<", "<<i[1]<<"]\n";

    return 0;
}
0 Answers
Related