c++ - 比较器的两种实现之间的区别
问题描述
我的代码中有一个名为 edge 的对象类,它需要定义运算符 < 来对对象进行排序。我以两种方式定义它,而另一种工作方式只是给出运行时错误(分段错误)。我想知道这东西是怎么工作的?我正在使用 std:: sort 来达到我的目的。
struct edge{
int u;
int v;
int w;
edge(int a, int b, int c) : u(a), v(b), w(c){}
bool operator<(const edge &other) const{
return (w <= other.w);
}
};
上面的代码给出了运行时错误。
struct edge{
int u;
int v;
int w;
edge(int a, int b, int c) : u(a), v(b), w(c){}
bool operator<(const edge &other) const{
return (w < other.w);
}
};
上面的代码工作正常。
解决方案
operator<
如果第一个参数小于第二个参数,则应返回 true,否则返回 false。排序算法依赖于这种行为,如果不是真的,可能会崩溃。
显然问题在于
bool operator<(const edge &other) const{
return (w <= other.w);
}
是如果两条边相等则返回true,这违反了上述规则,这意味着排序算法将不起作用。
推荐阅读
- f# - 存在同名属性时如何调用扩展方法?
- c# - OnDestroy() 和 OnApplicationQuit() 统一
- django - DRF:来自自定义查询集的 get_object
- json - Swagger 2.0 不验证空字符串
- node.js - 转换流中的http请求
- android - MainActivity 不启动
- node.js - nodejs在失去与mongodb的连接时崩溃
- oracle - 如何从 AWS RDS 中删除 oracle 跟踪和审计日志?
- pdf - 在 v 9.1.20 中生成 PDF 时,表头未在第二页显示文本
- powershell - 获取名称中带有通配符的子项