The following program is compiled with VC++ 2012.
#include <algorithm>
struct A
{
A()
: a()
{}
bool operator <(const A& other) const
{
return a <= other.a;
}
int a;
};
int main()
{
A coll[8];
std::sort(&coll[0], &coll[8]); // Crash!!!
}
If I change return a <= other.a;
to return a < other.a;
then the program runs as expected with no exception.
Why?
The answer for xorguy is pretty good.
I would just add some quote from the standard :
So xorguy explains it very well : You
comp
function says thata < b
whena == b
which doesn't follow the strict weak ordering rule...std::sort
requires a sorter which satisfies the strict weak ordering rule, which is explained hereSo, your comparer says that
a < b
whena == b
which doesn't follow the strict weak ordering rule, it is possible that the algorithm will crash because it'll enter in an infinite loop.