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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With