I realized that for quicksort to work, all infinities must be equal.
In other words, such a criterion is not enough:
class Entity { public: float value() const; bool valueIsInfinite() const; }; class Criterium { bool operator()(Entity left, Entity right)const { if (left.valueIsInfinite()) return false; return left.value() < right.value(); } } const Criterium criterium; QVector<Entity> container; qSort<container.begin(), container .end(), criterium>
This sorting fails because not all infinities are equal according to the criterion. The imbalance depends on the order in which the subjects enter the operator. I found out that this order does not work.
I need something like this:
class Criterium { bool operator()(Entity left, Entity right)const { if (left.valueIsInfinite() && right.valueIsInfinite()) return false; if (left.valueIsInfinite() && !right.valueIsInfinite()) return false; if (!left.valueIsInfinite() && right.valueIsInfinite()) return true; return left.value() < right.value(); } }
But suppose that instead
float Entity::value() const; bool Entity::valueIsInfinite() const;
I would like to use only
float Entity::value() const;
And bring him back
std::numeric_limits<float>::infinity();
in cases where
bool Entity::valueIsInfinite() const;
will return true.
Now I have tested this approach and it seems to have worked. But I am worried about other ways in which infinity may arise. For instance:
float otherInfinity = exp(std::numeric_limits<float>::infinity());
This infinity seems to be the same. But I want to be sure. I know that the C ++ standard does not mention the details of a floating point arithmetic implementation, but if I use gcc, is it safe in all cases? I mean, all infinities created equal in gcc? Is it safe to sort a container with floats that can contain infinities that have arisen at different times?