I have a class Customer
which has a member variable arrivalTime
. I have defined a getter function getArrivalTime()
. I am storing Customer
in a priority queue, and have defined a custom predicate as follows:
class ArrivalQueueCompare
{
public:
bool operator()(const Customer &a, const Customer &b)
{
return a.getArrivalTime() > b.getArrivalTime();
}
};
The priority queue is declared as:
std::priority_queue<Customer, std::vector<Customer>, ArrivalQueueCompare> arrivalQueue;
When I push four Customer
objects, a0
, a1
, a2
, and a3
, into the priority queue, with arrival times 20
, 0
, 50
, and 30
respectively, the priority queue seems to have stored them in the order a1
-a0
-a2
-a3
.
According to my predicate the order should be a1
-a0
-a3
-a2
, but the priority queue is storing them otherwise. Why might this be?
I have attached screenshots from Xcode's debugger screen as a proof: Screenshot 1 Screenshot 2 Screenshot 3 Screenshot 4
Update:
I am reading in lines from a file and creating Customer
objects with:
while (std::getline(file, line))
{
Customer newCustomer = createCustomerObject(line);
arrivalQueue.push(newCustomer);
}
The createCustomerObject()
function just creates, and returns, a Customer
object by initialising the member variables of Customer
using line
.
A priority_queue
doesn't store the object in a sorted fashion. It only guarantees that the first element is the largest one (depending on your compare).
So, observing the objects stored in a non-ordered fashion in the storage vector is expected.
When you start popping the objects with pop()
, you'll see the remaining objects get reordered.