Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 530
qutab Avatar asked May 03 '13 20:05

qutab


1 Answers

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);
}
like image 189
Lord Wolfenstein Avatar answered Oct 14 '22 14:10

Lord Wolfenstein