3

I need a priority_queue for my structs. I want to construct one using both initial data from an array and a custom comparator:

class mycomparison
{
public:
    mycomparison(const bool& maxOnTop=false, const int& compField = 0);
    ...
};

mergeRecord initialRecords[N]; // my array
mycomparison(false, field); // my custom comparator

std::priority_queue<mergeRecord, std::vector<mergeRecord>, mycomparison>
    recsHeap(???);

On the cplusplus reference, there is an example of how to initialize a priority_queue object with a comparator OR an array with initial values. How would I do both? I know I could insert them one by one, but this would cost O(nlogn) whereas passing them all at once is O(n).

2 Answers 2

4

The range constructor for std::priority_queue allows you to pass a comparator function in as an optional argument:

template <class InputIterator>
priority_queue (InputIterator first, InputIterator last,
                const Compare& comp = Compare(),
                const Container& ctnr = Container());

So just call it like this:

std::priority_queue<mergeRecord,std::vector<mergeRecord>,mycomparison>
    recsHeap(std::begin(initialRecords), std::end(initialRecords), mycomparison(false,field));
Sign up to request clarification or add additional context in comments.

Comments

2

In below example std::greater<int> is the compare function and myints is an integer array. We can create a priority_queue my_priority_queue as follows:

int myints[]= {10,60,50,20};
std::priority_queue<int, std::vector<int>, std::greater<int> >
                            my_priority_queue(myints,myints+4);

In your example:

priority_queue<mergeRecord,std::vector<mergeRecord>,mycomparison>
 recsHeap (mergeRecord, mergeRecord+ kWayMerge,mycomparison(false,field));

2 Comments

I saw that example on cplusplus.com, I mentioned I wanted a comparator argument as well.
@TartanLlama Thanks, that is valid. corrected the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.