类指针向量上的std :: sort()

qut*_*tab 7 c++ sorting stl stl-algorithm

我有一个类指针向量std::vector<Square*> listSquares.我想用类的一个属性作为关键字对它进行排序.这就是我正在做的事情

bool compById(Square* a, Square* b)
{
    return a->getId() < b->getId();
}

std::sort(listSquares.begin(), listSquares.end(), compById)
Run Code Online (Sandbox Code Playgroud)

但编译器说:错误:没有匹配函数调用'sort(std :: vector :: iterator,std :: vector :: iterator,<unresolved overloaded function type>)'

我在这做错了什么?

joh*_*ohn 12

为了使用它compById作为参数,std::sort它不应该是一个成员函数.这是错的

class Square
{
    bool compById(Square* a, Square* b)
    {
        return a->getId() < b->getId();
    }
    ...
};
Run Code Online (Sandbox Code Playgroud)

这个更好,

class Square
{
    ...
};

bool compById(Square* a, Square* b)
{
    return a->getId() < b->getId();
}
Run Code Online (Sandbox Code Playgroud)

  • 因为std :: sort如何在调用成员函数时知道要使用哪个对象?成员函数只能在对象上调用,但是std :: sort没有上下文来确定应该是哪个对象.大概你是从某个对象内部调用std :: sort,但是你没有将该对象传递给std :: sort.std :: sort对调用它的位置一无所知,它只知道传递给它的三个参数. (2认同)
  • 它可以是静态成员函数。普通(非静态)成员函数采用隐式第一个参数,即“this”,因此具有与非成员函数不同的签名。 (2认同)