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

qutab picture qutab · May 3, 2013 · Viewed 15.6k times · Source

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?

Answer

john picture john · May 3, 2013

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