std :: sort在std:指针向量上失败

mil*_*aki 4 c++ sorting stl vector stl-algorithm

以下代码在对矢量进行排序时崩溃.

#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;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Nic*_*las 22

bool operator() (Foo* p1, Foo *p2) const
{
    if (p1->x != p2->x) return p1->x < p2->x;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

std::sort需要一个排序函数来创建严格弱的排序.这.这是<=,这不是严格弱的排序.如果lhsrhs是equial然后comp(lhs, rhs)comp(rhs, lhs)必须都返回.

你的功能没有.因此,您会得到未定义的行为.

  • @miloszmaki完全删除`if`将具有相同的效果:) (3认同)