Std :: sort () for a class pointer vector

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

 bool compById(Square* a, Square* b) { return a->getId() < b->getId(); } std::sort(listSquares.begin(), listSquares.end(), compById) 

but the compiler says: error: there is no suitable function to call sorting (std :: vector :: iterator, std :: vector :: iterator, & unresolved overloaded function type>) '

what am i doing wrong here?

+7
source share
3 answers

To use compById as a parameter to std::sort , it does not have to be a member function. It is not right

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

The most important part that you are missing is that the arguments to the comparison function are const . Another type of return. If you discard the return type when declaring a function, the compiler will assume that it returns int , which is not the case in this case.

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

+3
source

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.

Note static before declaring a function and Square:: before the function name in the 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); } 
+1
source

All Articles