简体   繁体   English

std :: sort functor一行

[英]std::sort functor one line

I have declared a functor and made a call so std::sort with that functor as a parameter. 我已经声明了函子,并使用该函子作为参数进行了std :: sort调用。 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 , you can use a lambda 如果您的编译器支持 ,则可以使用lambda

std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(),
          [](const CString& item1, const CString& item2) {
              return MyClass::Compare( Order(_T("DESC")), item1, item2);
          });

without , 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 如果您考虑使用boost-bind ,则可以尝试使用

std::sort(AllObjects.GetData(), AllObjects.GetData() + AllObjects.GetSize(),
          boost::bind(MyClass::Compare, Order(_T("DESC")), _1, _2));

This is equivalent to std::bind in . 这等效于 std::bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM