Park Yeoung Jun Park Yeoung Jun - 6 months ago 31
Java Question

how to convert java priority queue to c++ priority queue?

I am rewriting Java code as C++ code and am having a problem duplicating Java's priority queue..

The Java priority queue's compare function looks like the following:

public int compareTo(Item that) {
if (this.dist < that.dist)
return -1;
if (this.dist > that.dist)
return 1;
return 0;
}


and I made a compare function in C++, however it is not working correctly:

struct cmp
{
bool operator()(Item it1, Item it2)
{
if(it1.dist > it2.dist)
return true;
}
};


it is my c++ code priority queue

I call priority queue like this

priority_queue<Item, vector<Item>, cmp> que;


but, Java's order and C++'s order is different..

help me please

If this is not enough example code, I can provide my whole code. Java and C++ code

Answer

Define your comparison operator as

struct cmp
{
    bool operator()(const Item & it1, const Item & it2)    // pass by a const reference
    {
        return it1.dist > it2.dist;
    }
};

You can also define it as a free function.