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

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

本文关键字:变量 结构 排序 一个      更新时间:2023-10-16

大家早上好,我正在尝试根据其中一个变量的值对结构中连接的 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() 包含在库中,并对括号中的数组执行快速排序。请帮忙,泰

尝试以下操作

#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() );