Search code examples
c++structquicksortboolean-operations

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


Good morning everyone, I'm trying to sort 3 variables connected in a struct based on the values of one of them. To make myself clear I have a structed type of variable called edge and it has 3 ints: edge.a edge.b and edge.w. I want to sort edge by the values on edge.w. I found out that to achieve that i need to use bool operators but i haven't found out how yet. This is my code:

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

sort() is included in a library and executes quicksort on the array on parenthesis. Please help, TY


Solution

  • Try the following

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

    Or

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

    The other approach is the following

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