struct Object
{
int x;
int y;
bool isXValid()
{
return x > 0;
}
};
bool mySort(const Object& lhs, const Object& rhs)
{
// Note the short-circuit here
bool isValidForCheck = lhs.isXValid() && rhs.isXValid();
// rhs may be valid because short-circuit, or both may be invalid
if (isValidForCheck)
{
return lhs.x < rhs.x;
}
return lhs.y < rhs.y;
}
int main()
{
std::vector<Object> myVec;
// random populating of myVec
std::sort(myVec.begin(), myVec.end(), mySort);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的比较函数是反射性的,但不尊重传递性.