Yes, I know this is a repeat question and I already know that the anwser im looking for is here:
Sorting a vector of objects by a property of the object
However I have problems converting this to my own code. I’m looking at this code snippet from the above question:
struct SortByX
{
bool operator() const(MyClass const& L, MyClass const& R) {
return L.x < R.x;
}
};
std::sort(vec.begin(), vec.end(), SortByX();
What I do not understand is what is being represented by MyClass const & L, and MyClass const & R. And I am not grasping how I can apply this to my code.
To give a bit more detail I am putting 3 sort methods into a wrapper class of a vector of objects that have parameters of (string, double, double, double, bool). And the over all goal is to sort the vector by the string, the bool and any one out of the 3 doubles.
This is the lastest version I have:
void StationVector::sortByGrade(int kindOfGas) {
struct SortByGrade {
int kindOfGas;
SortByGrade(int kindOfGas) :
kindOfGas(kindOfGas) {
}
bool operator()(GasStation const &L, GasStation const & R) const {
return L.getPrice(kindOfGas) < R.getPrice(kindOfGas);
}
};
std::sort(localStations.begin(), localStations.end(),
SortByGrade(kindOfGas));
}
the line SortByGrade(kindOfGas)) gives me the following error:
no matching function for call to `sort(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >, model::StationVector::sortByGrade(int)::SortByGrade)’
LandR, in this case are two items (instances of your classMyClass) from the container that are being compared, withLon the left of the less-than operator andRon the right. They are passed in by const-reference.In your own
bool operator() const(MyClass const& L, MyClass const& R), you need to compare the three data members you mention in your question, vitally remembering to apply strict weak ordering. ReturntrueifLis “less than”Randfalseotherwise.Following updates to the question…
It looks like you wish to pass a variable into your functor. You do this by creating a constructor, like this SSCCE (which compiles here):
Note: The
constqualifier comes after the argument list and not after the method name.Also, please don’t put the entire method on one line, it makes it very difficult to read.