I want to reverse sort a custom container with custom objects, so when sorting this way: (this is part of the .cpp)
bool PictureContainer::isGreater(const Picture& i, const Picture& j) {
return (i.getId() > j.getId());
}
void PictureContainer::sortRev() {
sort(picture, picture tam, isGreater());
//< If I try with isGreater, without parenthesis, it says I need to make it static and then it gives same error again.
}
this is part of the .h
class PictureContainer {
private:
int size;
Picture *picture;
public:
PictureContainer();
PictureContainer(int maxSize);
bool isGreater (const Picture& i, const Picture& j);
void sortRev();
CodePudding user response:
It's impossible to use a non-static member function directly as the comparator for std::sort(). There are a few options:
Mark
PictureContainer::isGreateras static, and passPictureContainer::isGreatertostd::sort().Since the implementation of
isGreaterdoes not access anything that's only available from thePictureContainerclass, we may also make it a free function and passisGreatertostd::sort().In case the implementation of
isGreaterhas to access some members (or member functions) that's only available within an instance ofPictureContainer, we may use a lambda inside the implementation ofPictureContainer::isRevas the argument. This is the most flexible solution. For example:
void PictureContainer::sortRev() {
sort(picture, picture tam, [this](const Picture& lhs, const Picture& rhs) {
return this.isGreater(lhs, rhs);
});
}
CodePudding user response:
isGreater() is a member function of PictureContainer. You cannot pass it to std::sort like that. The easiest way to fix this is to make isGreater() a stand-alone non-member function.
Generally, you can pass pointers to member functions around, but the syntax is convoluted, and you need the object of the class. https://www.tutorialspoint.com/function-pointer-to-member-function-in-cplusplus
