codefluent
codefluent

Reputation: 135

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;  
}

Upvotes: 1

Views: 60

Answers (1)

Jarod42
Jarod42

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

Related Questions