c++ - C++ logical negated comparison operator doesn't work
问题描述
I have a pretty simple class foo
, that implements the <
operator. I tried to implement a descending sort by negating the result of the operator like here:
std::sort(foos_.begin(), foos_.end(),
[](Foo& a, Foo& b) { return !(a < b); }
);
Unfortunately, this gives me a SIGSEGV
error. I guess because the result of the comparison is not reasonable. But I'm wondering why this is? Shouldn't !(a < b)
be the same as (b < a)
?
The following code works as expected:
std::sort(foos_.begin(), foos_.end(),
[](Foo& a, Foo& b) { return (b < a); }
);
The implementation of the operator is straight forward:
bool Foo::operator<(Foo const& a) const {
return this->some_float_value < a.some_float_value;
}
解决方案
不
!(a < b)
应该一样(b < a)
吗?
不,!(a < b)
相当于b <= a
。
<=
并且>=
不尊重严格的弱排序。
你需要:
std::sort(foos_.begin(), foos_.end(),
[](const Foo& a, const Foo& b) { return b < a; }
);
推荐阅读
- c++ - C ++可以在'''.close()'''之后关闭'''fstream'''变量吗?
- powershell - 如何使用 powershell 将参数传递给 ADF 管道
- java - ImageView 不正确的 XY 坐标
- ruby-on-rails - 如何将haml与react js集成。我想使用Haml文件渲染react组件?
- spring-boot - Spring Boot Apache Camel 应用程序在容器中时不服务请求
- java - 如何在java上使用多个用户帐户的用户登录属性
- facebook-javascript-sdk - 我收到此错误“找不到变量:FBSDKApplicationDelegate”
- java - 我的 Hibernate CRUD 没有在表中保存数据,但它显示表为空
- python-3.x - 如何计算指定索引以外的元素的总和?
- php - 随机化对象数组的一部分