首页 > 解决方案 > 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;  
}

标签: c++

解决方案


!(a < b)应该一样(b < a)吗?

不,!(a < b)相当于b <= a

<=并且>=不尊重严格的弱排序。

你需要:

std::sort(foos_.begin(), foos_.end(), 
  [](const Foo& a, const Foo& b) { return b < a; }
);

推荐阅读