std::sort functor one line

瘦欲@ 提交于 2019-12-11 10:24:29

问题


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:


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.



来源:https://stackoverflow.com/questions/15181378/stdsort-functor-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!