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