Search code examples
c++sortingstlstl-algorithm

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


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?


Solution

  • 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();
    }