I have a class with a function
MyClass::doStuff(std::vector<MyCustomData*> toSort) { ...
in which I call
std::sort(toSort.begin(), toSort.end(), MyClass::SortByZ());
myClass::SortByZ() is a custom comparator. Now this works but I would like to achieve the following:
I have several classes, which should each have its own comparator functor to sort "MyCustomData". So e.g. Class1... should have
class Class1 {
struct SortData {
bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
return lhs->something1 > rhs->something1;
}
};
//...many more functions/vars
}
while Class2 has a different comparator functor for the same datatype eg
class Class2 {
struct SortData {
bool operator ()(MyCustomData *lhs, MyCustomData *rhs) {
return lhs->something2 > rhs->something2;
}
};
//...many more functions/vars
}
Now I would like to be able to call the function MyClass::doStuff(...) with either
doStuff(myData, Class1::SortData)
or
doStuff(myData, Class2::SortData)
and the function MyClass::doStuff(...) should use the respective Sort-Order.
I did not find out a way of doing this, is there one? I would like a simple solution (doesn't have to support templates or anything). I would be willing to use boost if I needed that, but a solution without boost would be preferred.
I hope I was able to describe what I want to achieve? Thanks for any help!
You will have to make doStuff a template:
template <typename Comparator>
void doStuff(std::vector<MyCustomData*> toSort, Comparator compare) {
// ...
std::sort(toSort.begin(), toSort.end(), compare);
// ...
}
Also, it might want to take the first argument by reference. As it is, it will sort a copy of the argument, discard that copy, and leave the caller's vector untouched; although perhaps that's what you want.
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