std :: sort functor一行 [英] std::sort functor one line
问题描述
我已经声明了函子,并使用该函子作为参数进行了std :: sort调用.代码:
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?
推荐答案
如果您的编译器支持 c ++ 11 ,则可以使用Lambda
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);
});
没有c ++ 11 ,您可以使用函数而不是函子来简化它
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"))));
如果您考虑使用 boost-绑定,您可以尝试使用
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));
这等效于std::bind
"/questions/tagged/c%2b%2b11" class ="post-tag" title =显示已标记'c ++ 11'的问题"" rel ="tag"> c ++ 11 .
这篇关于std :: sort functor一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!