了解 STL 的比较器仿函数

Understanding a Comparator functor for STL

所以我一直在 STL 中使用比较仿函数,但从未真正理解返回 true 或 false 的含义。我不得不 运行 它并一直调整仿函数。例如假设我有以下代码

struct functor
{
    // does returning true place a before b ?
    bool operator()(int a,int b)
    {
        if (a < b)
            return true;
        return false;
    }
};

int main() 
{
    std::priority_queue<int, std::vector<int>,functor> q;
    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);
}

谁能澄清一下

bool operator()(int a,int b)
    {
        if (a < b)
            return true;
        return false;
    }

是否在b之前返回一个真实的地方a?我正在尝试想出类似 "if a is less than b than return true and true means a will be placed before b" 的东西,但显然这是不正确的

< 排序是惯例。您的代码

bool operator()(int a,int b)
{
    if (a < b)
        return true;
    return false;
}

相同
bool operator()(int a, int b)
{
    return a < b ;
}

另外,看看Operator< and strict weak ordering

为什么不直接这样做,因为它更简单:

bool operator()(int a, int b)
{
    return a < b
}

您需要为优先级队列提供排序函数的函数应该是一个二元函数,如果 b 大于 a,或者第一个参数大于 b,则 returns 为真。

如果该条件不成立,排序函数可能在内部使用两个值的简单交换。

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

http://www.cplusplus.com/reference/algorithm/sort/

您可以随时查看文档。

来自priority_queue

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

Compare - A Compare type providing a strict weak ordering.

然后,检查 Compare:

The concept Compare is a set of requirements expected by some of the standard library facilities from the user-provided function object types.

The return value of the function call operation applied to an object of type Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this Compare type, and false otherwise.

这意味着,functor::operator() 应该接受两个参数(ab)和 return true 如果 a "appears before" b 而 "appears before" 规则由 functor::operator() 的实现定义(此实现必须符合 Compare 概念强加的要求)。

是的,如果你的函数是

bool operator(T a, T b); 

如果returns为真,则表示a在排序顺序中位于b之前。但是,优先级队列是有序的,因此如果 a 放在 b 之前,则 b 在队列中将高于 a。所以如果

bool operator (T a, T b) { return a < b; }
使用

时,"largest" 元素将位于队列的顶部。