Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::sort fails on std:vector of pointers

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?

like image 532
miloszmaki Avatar asked Nov 29 '22 16:11

miloszmaki


1 Answers

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.

like image 180
Nicol Bolas Avatar answered Dec 01 '22 06:12

Nicol Bolas