Std :: sort failed on std: pointer vector

The following code fails while sorting a 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?

+4
source share
1 answer
 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 strictly weak order . This is not true. This is <= , which is not a strictly weak ordering. If lhs and rhs are equal, then comp(lhs, rhs) and comp(rhs, lhs) should return false.

Your function does not work. This way you get undefined behavior.

+22
source

Source: https://habr.com/ru/post/1432588/


All Articles