简体   繁体   English

优先级队列定制比较器的返回值表示什么?

[英]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 . 我不明白的是返回truefalse的含义。 If I return true , which element gets pushed first to the queue, and which, if I return false ? 如果我返回true ,那么哪个元素首先被推送到队列,而哪个返回false呢?

std::priority_queue is a max heap, which by default uses std::less (which is a function object which uses operator< ). std::priority_queue最大堆,默认情况下使用std::less (这是使用operator<的函数对象)。 That implies that if the comparison returns false , the first argument goes closer to the top. 这意味着,如果比较返回false ,则第一个参数更接近顶部。 From cppreference : 来自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() . 可以提供用户提供的Compare来更改顺序,例如,使用std::greater<T>会使最小的元素显示为top()

The standard reference is [alg.heap.operations] . 标准参考是[alg.heap.operations]


Side-note #1: Avoid writing if (expr) return true; else return false; 旁注1:避免if (expr) return true; else return false; if (expr) return true; else return false; in favor of simply return expr; 支持简单地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. 旁注2:您的operator()应该是const成员函数,并通过引用const接受其参数,以避免不必要的复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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