I have declared a functor and made a call so std::sort with that functor as a parameter. Code:
struct
{
bool operator() (const CString& item1, const CString& item2){
return MyClass::Compare( Order(_T("DESC")), item1, item2);
}
}Comparer;
std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(), Comparer);
Simple question: can I do this in one line?
If your compiler supports c++11, you can use a lambda
std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(),
[](const CString& item1, const CString& item2) {
return MyClass::Compare( Order(_T("DESC")), item1, item2);
});
without c++11, you can simplify it only a little bit by using a function instead of a functor
static inline bool Comparer(const CString& item1, const CString& item2) {
return MyClass::Compare(Order(_T("DESC")), item1, item2);
}
and use that as the last parameter.
Unfortunately (?), there are only function wrappers for unary or binary function objects. If there were wrappers for ternary function objects too, you could do something similar to
std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(),
std::bind1st(std::ptr_fun(MyClass::Compare), Order(_T("DESC"))));
If you consider using boost - bind, you can try this instead
std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(),
boost::bind(MyClass::Compare, Order(_T("DESC")), _1, _2));
This is equivalent to std::bind
in c++11.