在其中一个变量上对多变量结构进行排序

Sorting multi-variable struct on one of it's variables

大家早上好, 我正在尝试根据其中一个变量的值对在结构中连接的 3 个变量进行排序。为了让自己清楚,我有一个结构化类型的变量称为 edge,它有 3 个整数:edge.a edge.b 和 edge.w。我想按 edge.w 上的值对边缘进行排序。我发现要实现这一点,我需要使用 bool 运算符,但我还没有找到方法。这是我的代码:

struct type{
   int a,b,w;
   bool operator<(const edge&A) const{
        return w<A.w;
   };
};
type edge[6];
sort (edge);

sort() 包含在库中,对括号内的数组执行快速排序。 请帮忙, TY

尝试以下方法

#include <algorithm>

//...

struct type{
   int a,b,w;
   bool operator<(const type& A) const{
        return w<A.w;
   };
};

type edge[6];

//...

std::sort( edge, edge + 6 );

或者

#include <algorithm>
#include <iterator>

//...

struct type{
   int a,b,w;
   bool operator<(const type& A) const{
        return w<A.w;
   };
};

type edge[6];

//...

std::sort( std::begin( edge ), std::end( edge ) );

另一种方法如下

#include <algorithm>
#include <iterator>

//...

struct type{
   int a,b,w;

   struct sort_by_a
   {
       bool operator ()(const type &lhs, const type &rhs ) const
       {
           return  lhs.a < rhs.a;
       }
   };
   struct sort_by_b
   {
       bool operator ()(const type &lhs, const type &rhs ) const
       {
           return  lhs.b < rhs.b;
       }
   };
   struct sort_by_w
   {
       bool operator ()(const type &lhs, const type &rhs ) const
       {
           return  lhs.w < rhs.w;
       }
   };
};

type edge[6];

//...

std::sort( std::begin( edge ), std::end( edge ), type::sort_by_a() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_b() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_w() );