std::sort() on a vector of Class pointers

╄→尐↘猪︶ㄣ 提交于 2021-01-26 07:13:34

问题


I have a vector of class pointers std::vector<Square*> listSquares. I want to sort it with one of the attributes of the class as the key. This is what I'm doing

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

std::sort(listSquares.begin(), listSquares.end(), compById)

but the compiler says: error: no matching function for call to 'sort(std::vector::iterator, std::vector::iterator, <unresolved overloaded function type>)'

what am I doing wrong here?


回答1:


In order to use compById as a parameter to std::sort it should not be a member function. This is wrong

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

This is better,

class Square
{
    ...
};

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



回答2:


The most important part you're missing is that the arguments to the compare function are const. Another is the return type. If you leave out the return type when declaring a function, the compiler will assume it returns int which is not correct in this case.

And of course the comparison function has to be in scope when you call the std::sort function.




回答3:


You can use a member function. But you need to define it as a static member function and call it from the class, not an instance of the class.

Notice static before the function declaration, and Square:: before the function name in sort.

class Square
{
    /*...*/
public:
    static bool compById(const Square* a, const Square* b)
    {
        return a->getId() < b->getId();
    }
};

main()
{
    /*...*/
    std::sort(listSquares.begin(), listSquares.end(), Square::compById);
}


来源:https://stackoverflow.com/questions/16366978/stdsort-on-a-vector-of-class-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!