Sorting a vector of custom objects

后端 未结 13 3007
既然无缘
既然无缘 2020-11-21 05:14

How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a fu

13条回答
  •  面向向阳花
    2020-11-21 05:54

    In the interest of coverage. I put forward an implementation using lambda expressions.

    C++11

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

提交回复
热议问题