【问题标题】:How does the comparator function work in Priority Queue C++ STL?比较器函数在优先队列 C++ STL 中如何工作?
【发布时间】:2020-04-07 04:39:31
【问题描述】:
class Student
{
    public:
    string a;
    int age;
    Student(string a,int age)
    {
        this->a=a;
        this->age=age;
    }
};

bool operator<(const Student &a,const Student &b)
{
    return a.age<b.age;
}

int main()
{
    priority_queue<Student> pq;
    Student a("max",1);
    Student b("john",1);
    pq.push(a);
    pq.push(b);
    cout << pq.top().a << " " << pq.top().age << endl;
    pq.pop();
    cout << pq.top().a << " " << pq.top().age << endl;
    pq.pop();
}

输出是- 最多 1 个
约翰 1

关于更改比较器功能

bool operator<(const Student &a,const Student &b)
{
    return a.age<=b.age;
}

输出是-> 约翰 1

最多 1 个

谁能解释一下比较器函数在

【问题讨论】:

  • 一种 Compare 类型,提供 strict 弱排序。 &lt;= 不符合此要求。因此,您会得到未定义的行为,并且您的问题是非法的。
  • @jamesgem this 解释得好一点吗?
  • 什么是严格的弱排序?
  • @jamesgem -- 然后使用大于只比较,即&gt;。并且永远不要使用&lt;=&gt;= 来确定一个项目是否在另一个之前。如果您阅读给出的答案,您就会明白为什么它不起作用,因为它对于两个相等的项目是模棱两可的。 Strict-weak-order 只想知道哪个项目放在另一个之前,如果你对那个问题给出了相互矛盾的答案,那么程序就会变得混乱并且你会得到奇怪的错误。
  • 这里是some documentation,了解比较函数是如何工作的。让很多人感到困惑的是,您需要返回 false 以获得相同的对象。

标签: c++ stl comparator priority-queue


【解决方案1】:

源码如下(vs2019测试):

// FUNCTION TEMPLATE _Debug_lt_pred
template <class _Pr, class _Ty1, class _Ty2,
    enable_if_t<is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(
    noexcept(_Pred(_Left, _Right)) && noexcept(_Pred(_Right, _Left))) {
    // test if _Pred(_Left, _Right) and _Pred is strict weak ordering, when the arguments are the cv-same-type
    const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
    if (_Result) {
        _STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
    }

    return _Result;
}

你可以看到模棱两可的比较是无效的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 2020-10-14
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2021-06-18
    相关资源
    最近更新 更多