std::sort functor one line

2019-07-25 08:46发布

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?

1条回答
别忘想泡老子
2楼-- · 2019-07-25 09:28

If your compiler supports , 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 , 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 .

查看更多
登录 后发表回答