Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ spaceship operator multilevel compare?

Does the new C++20 spaceship operator allow a concise way of expressing short-circuited multiple-criteria comparison? Something better than this:

const firstCriteriaComparisonResult = lhs.x <=> rhs.x;
return firstCriteriaComparisonResult != 0 ? firstCriteriaComparisonResult : lhs.y <=> rhs.y;
like image 545
Szczepan Hołyszewski Avatar asked Mar 02 '23 14:03

Szczepan Hołyszewski


1 Answers

The usual tie-and-compare approach works with spaceship too:

return std::tie(lhs.x, lhs.y) <=> std::tie(rhs.x, rhs.y);
like image 159
T.C. Avatar answered Mar 14 '23 23:03

T.C.