简体   繁体   中英

What does the return value of a priority queue custom comparator signify?

From what I could gather about a custom comparator for a priority queue of the following structure, it looks like this

struct event
{
    int index, arrival, duration, type, end;
};

struct compare
{
    bool operator() (event a, event b)
    {
        if (a.arrival < b.arrival) return true; // which one gets pushed first?
        else return false;
    }
};
...
priority_queue < event, vector <event>, compare > pq;

What I did not understand is the meaning of returning true or false . If I return true , which element gets pushed first to the queue, and which, if I return false ?

std::priority_queue is a max heap, which by default uses std::less (which is a function object which uses operator< ). That implies that if the comparison returns false , the first argument goes closer to the top. From cppreference :

A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.

A user-provided Compare can be supplied to change the ordering, eg using std::greater<T> would cause the smallest element to appear as the top() .

The standard reference is [alg.heap.operations] .


Side-note #1: Avoid writing if (expr) return true; else return false; if (expr) return true; else return false; in favor of simply return expr;

Side-note #2: Your operator() should be a const member function and take its arguments by reference to const to avoid unnecessary copies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM