Reputation: 135
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;
}
Upvotes: 1
Views: 60
Reputation: 217275
Shouldn't
!(a < b)
be the same as(b < a)
?
no, !(a < b)
is equivalent to b <= a
.
<=
and >=
doesn't respect strict weak ordering.
You need:
std::sort(foos_.begin(), foos_.end(),
[](const Foo& a, const Foo& b) { return b < a; }
);
Upvotes: 3