Search code examples
c++pointersstructpriority-queue

reordering priority_queue based on condition c++


I am trying to reorder priority_queue based on user demand.

This is the data struct:

struct Person { 

    int age; 

    float height; 
};

I used this struct separately to reorder it in a decreasing way

struct CompareHeight { 
    bool operator()(Person const& p1, Person const& p2) 
    { 
        // return "true" if "p1" is ordered  
        // before "p2", for example: 
        return p1.height > p2.height; 
    } 
} HI; 

and I used this struct separately to reorder it in an increasing way

struct CompareHeightInv { 
    bool operator()(Person const& p1, Person const& p2) 
    { 
        // return "true" if "p1" is ordered  
        // before "p2", for example: 
        return p1.height < p2.height; 
    } 
} HD; 

and I call each speratlly by:

priority_queue<Person, vector<Person>, CompareHeightInv> inc; 

priority_queue<Person, vector<Person>, CompareHeight > dec; 

My question is: is there a way that like this

class Foo {
private:
     ...
     priority_queue<Person, vector<Person>, something> myQueue; 
     ...
public:
     Foo (bool flag) {
          if (flag)
             myQueue is increasing
          else
             myQueue is deacreasing
     }

}

Solution

  • One of the way and probably simplest, is to pass additional flag to your comparator and have only one:

    struct CompareHeight { 
        CompareHeight( bool asc ) : ascending( asc ) {}
        bool operator()(Person const& p1, Person const& p2) 
        { 
            if(ascending) return p1.height < p2.height; 
            return p1.height > p2.height; 
        } 
        bool ascending;
    };
    

    then use it:

    CompareHeight comparator( str == "increasing" );
    priority_queue<Person, vector<Person>, CompareHeight> queue( comparator );
    

    or just one line:

    priority_queue<Person, vector<Person>, CompareHeight> queue( CompareHeight( str == "increasing" ) );
    

    Otherwise you can use std::function as a type and pass specific type or use inheritance and have both comparators to derive from common base. Both ways are significantly more verbose.