vgeta
vgeta

Reputation: 507

Switch between min heap and max heap based on a flag

I have defined a minheap as follows

typedef priority_queue<megePartitions_t,vector<megePartitions_t>,compareMergePartition> mergePartitionFilesQ_t;

The comparator is defined as follows

struct compareMergePartition
{
   bool operator()(const megePartitions_t &lhs,const megePartitions_t &rhs)
   {
      return *(lhs._pair) > *(rhs._pair);
   }
};

I am using the defined minheap as follows

mergePartitionFilesQ_t mergeQ

Now, I want to switch between minheap and maxheap based on a flag, Should I change the comparator's constructor to take in the flag and use it to flip between greater or lesser than comparision or is there a better way. Thank you for your help.

Answer : I felt there is no need for functors so I switched to function pointers, and chose appropriate function based on flag.

if(m_builtAcending)
    comparator = compareMergePartitionAsc;
else
    comparator = compareMergePartitionDes;
mergePartitionFilesQ_t mergeQ(comparator);

Thank you freitass for your help

Upvotes: 0

Views: 301

Answers (2)

freitass
freitass

Reputation: 6694

You can define a constructor to your functor that receives a comparison function and instantiate it passing std::less or std::greater, as follows:

template<class Comp>
struct compareMergePartition
{
   Comp comp;
   compareMergePartition(Comp comp) : comp(comp) {}
   bool operator()(const megePartitions_t &lhs,const megePartitions_t &rhs)
   {
      return comp(*(lhs._pair), *(rhs._pair));
   }
};

// Min heap
typedef priority_queue<megePartitions_t,vector<megePartitions_t>,compareMergePartition(std::less<megePartitions_t>())> mergePartitionFilesQ_t;

// Max heap
typedef priority_queue<megePartitions_t,vector<megePartitions_t>,compareMergePartition(std::greater<megePartitions_t>())> mergePartitionFilesQ_t;

Edit: This answer was given assuming you know what you want at construction time. It is not suitable for on-the-fly changes.

Upvotes: 1

Kourosh
Kourosh

Reputation: 274

One way is to add a constructor as you mentioned, but since when you change the flag your data order will not be correct; you'll have to reconstruct the whole priority queue. So maybe you can have two queues, one for min-heap and one for max-heap? And copy the data to the other when the flag's value is changed? (Implementation provided by freitass is a good one IMHO)

Upvotes: 0

Related Questions