The following code crashes while sorting the vector.
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
struct Foo
{
int x;
// int y;
Foo() : x(0) {}
};
struct Cmp
{
bool operator() (Foo* p1, Foo *p2) const
{
if (p1->x != p2->x) return p1->x < p2->x;
// if (p1->y != p2->y) return p1->y < p2->y;
return true;
}
};
int main()
{
vector<Foo*> v;
for (int i=0; i<17; i++) // weird thing, doesn't crash if
// I put a number less than 17 !!!
{
Foo *ptr = new Foo();
if (ptr) v.push_back(ptr);
}
sort(v.begin(), v.end(), Cmp());
return 0;
}
Why is this so?
bool operator() (Foo* p1, Foo *p2) const
{
if (p1->x != p2->x) return p1->x < p2->x;
return true;
}
std::sort
requires a sort function that creates a strict-weak ordering. This does not. This is <=
, which is not a strict-weak ordering. If lhs
and rhs
are equial then comp(lhs, rhs)
and comp(rhs, lhs)
must both return false.
Your function does not. Thus, you get undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With