排序std :: vector< myclass>在一行使用从STL的排序功能 [英] Sort std::vector<myclass> in one line using sort function from STL

查看:172
本文介绍了排序std :: vector< myclass>在一行使用从STL的排序功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是关于使用STL算法类中的函数 sort std :: vector< myclass> >
标准方式是: sort(v.begin(),v.end(),& myfunct)

其中 myfunct 是:

Question is about sorting std::vector<myclass> using function sort from STL's algorithms class.
Standard way is : sort(v.begin(), v.end(), &myfunct)
where myfunct is:

bool myfunct( myclass first, myclass second ) {   
    if (first.value < second.value)   
        return true;   
    else return false;   
}

上述方法需要多行。我很好奇如何做到一条线。是否可能定义函数比较排序函数里面的myclass对象?可能以某种方式使用这个(a< b)? a:b 。我记得在C#中有这样的东西,但我忘了它是如何调用的。

Approach above takes more than one line. I am curious how to do it in one line. Is it possible define function that compares myclass objects inside sort function? May be somehow use this (a < b) ? a : b. I remember that there is something like this in C#, but I forgot how is it called. Is it possible to do in C++.

推荐答案

首先,你可以返回 first.value< second.value 但这不会摆脱的功能。在C ++ 2011中,您可以使用lambda函数:

First, you can just return first.value < second.value but this doesn't get rid of the function. In C++2011 you can use a lambda function:

   std::sort(begin, end, [](myclass const& f, myclass const& s){ return f.value < s.value; });

没有C ++ 2011我认为你需要一个函数对象,因为没有什么

Without C++2011 I think you'll need a function object because there isn't anything which projects your class to the value you actually want to compare.

BTW,你绝对想通过引用你的比较函数传递一切,但最简单的对象。

BTW, you definitely want to pass everything but the most trivial objects by reference to your comparison function.

这篇关于排序std :: vector&lt; myclass&gt;在一行使用从STL的排序功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆