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).
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));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.