目录
1. 这是自己遇到的问题,仅做错误记录使用,以前没有做记录的习惯。
2. invalid comparator中文翻译:无效的比较器,尤其是使用sort函数时容易发生此问题。
3. 源码如下
#include <list>
#include <string>
#include <iostream>
using namespace std;
struct Info
{
int id;
string name;
bool operator<(const Info rh) const
{
return id <= rh.id;
//return id < rh.id;
}
};
void func()
{
list<Info> infos;
infos.push_back({1, "1"});
infos.push_back({3, "3"});
infos.push_back({3, "3"});
infos.push_back({2, "2"});
infos.sort();
}
output:
编译正常,运行崩溃
4. 分析原因:
4.1崩溃的位置在这里
const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
if (_Result)
{
_STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
}
4.2 原因:
template<>
struct less<void>
{ // transparent functor for operator<
typedef int is_transparent;
template<class _Ty1,
class _Ty2>
constexpr auto operator()(_Ty1&& _Left, _Ty2&& _Right) const
-> decltype(static_cast<_Ty1&&>(_Left)
< static_cast<_Ty2&&>(_Right))
{ // transparently apply operator< to operands
return (static_cast<_Ty1&&>(_Left)
< static_cast<_Ty2&&>(_Right));
}
};
结论:
- 使用less时,传入的比较器必须是operator<,而不能是operator<=。
- less就是less,less不是less_equal
- 不要想加上等于就可以不调换相等的元素了,这是错误的想法(在说自己)
4.3 代码修正
bool operator<(const Info rh) const
{
// return id <= rh.id;
return id < rh.id;
}
原文链接: https://www.cnblogs.com/faithlocus/p/13404111.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200945
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!