比较器函数如何在优先级队列 C++ STL 中工作?
How does the comparator function work in Priority Queue C++ STL?
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
有人可以解释一下在 < 和 <= 的情况下比较器功能如何变化吗?
源码如下(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;
}
可以看到模糊比较无效
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
有人可以解释一下在 < 和 <= 的情况下比较器功能如何变化吗?
源码如下(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;
}
可以看到模糊比较无效