为了账号安全,请及时绑定邮箱和手机立即绑定

对自定义对象的向量进行排序

对自定义对象的向量进行排序

C++ C
拉丁的传说 2019-05-31 11:13:19
对自定义对象的向量进行排序如何对包含自定义(即用户定义)对象的向量进行排序。可能,标准STL算法排序应该使用在自定义对象中的一个字段(作为排序键)上操作的谓词(函数或函数对象)。我在正确的轨道上吗?
查看完整描述

3 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

为了保险起见。我提出了一个实现Lambda表达式.

C+11

#include <vector>#include <algorithm>using namespace std;vector< MyStruct > values;sort( values.begin( ), values.end( ), [ ]
( const MyStruct& lhs, const MyStruct& rhs ){
   return lhs.key < rhs.key;});

C+14

#include <vector>#include <algorithm>using namespace std;vector< MyStruct > values;sort( values.begin( ), values.end( ), [ ]
( const auto& lhs, const auto& rhs ){
   return lhs.key < rhs.key;});


查看完整回答
反对 回复 2019-05-31
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

您可以使用函子作为std::sort,或者你可以定义operator<在你的班上。

struct X {
    int x;
    bool operator<( const X& val ) const { 
        return x < val.x; 
    }};struct Xgreater{
    bool operator()( const X& lx, const X& rx ) const {
        return lx.x < rx.x;
    }};int main () {
    std::vector<X> my_vec;

    // use X::operator< by default
    std::sort( my_vec.begin(), my_vec.end() );

    // use functor
    std::sort( my_vec.begin(), my_vec.end(), Xgreater() );}


查看完整回答
反对 回复 2019-05-31
  • 3 回答
  • 0 关注
  • 591 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信