0

I don't understand why I am getting different result for similar code in C++ and Java. May be I am doing something wrong somewhere. I actually want to implement priority queue with custom comparator in C++ just like the one implemented in Java here.

Code in Java

import java.util.Comparator;
import java.util.PriorityQueue;
public class HelloWorld 
{
    static class PQsort implements Comparator<Integer> 
    {
        public int compare(Integer a, Integer b)
        {
            return Integer.compare(a, b);
        }
    }
    public static void main(String[] args) 
    {
        int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
        PQsort pqs = new PQsort();
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(11,pqs);
        for (int x : ia) 
        {
            pq.offer(x);
        }
        System.out.println("pq: " + pq);
    }
} 

Output

pq: [1, 3, 5, 8, 4, 7, 6, 10, 9]

Code in C++

#include <vector>
#include <iostream>
#include <queue>
using namespace std;

struct comp
{
    bool operator()(const int a, const int b) const
    {
         return b < a;
    }
};
int main()
{
    priority_queue<int, vector<int>, comp> pq;
    int ia[] = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
    for (int i=0;i<9;i++) 
    {
        pq.push(ia[i]);
    }
    while (!pq.empty())
    {
        std::cout << ' ' << pq.top();
        pq.pop();
    }
    return 0;
}

Output

 1 3 4 5 6 7 8 9 10 
Ankan Kumar Giri
  • 243
  • 1
  • 3
  • 12
  • The comparator should return a `bool` in the c++ version. – πάντα ῥεῖ Jan 10 '16 at 10:41
  • @πάνταῥεῖ Even more. It should implement a strict weak ordering. `int` is convertible to `bool` anyway. – juanchopanza Jan 10 '16 at 10:42
  • @juanchopanza I tried the answer that you had referred but it just gives me sorted queue – Ankan Kumar Giri Jan 10 '16 at 10:49
  • @AnkanKumarGiri You need to implement the strict weak ordering that matches your intended priority. `a-b` isn't a strict weak ordering. It evaluates to `true` for all `a, b` such that `a != b`. – juanchopanza Jan 10 '16 at 10:52
  • 1
    Note that the iterator returned by the priority queue in Java offers no guarantee about the order of the elements (_" The iterator does not return the elements in any particular order."_). Thus the `println` call won't necessarily print the elements in the queue according to the comparator you provided. – Alexis C. Jan 10 '16 at 10:52
  • @AlexisC. Thanks, the iterator was acually returning in random order. – Ankan Kumar Giri Jan 10 '16 at 11:04
  • @juanchopanza Ok, so i need to change the compare function...Got it. Thanks a ton – Ankan Kumar Giri Jan 10 '16 at 11:05

0 Answers0