简体   繁体   English

如何用初始数据和自定义比较器声明stl :: priority_queue?

[英]How to declare an stl::priority_queue with initial data and custom comparator?

I need a priority_queue for my structs. 我需要我的结构的priority_queue 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. 在cplusplus参考上,有一个示例,说明如何使用比较器具有初始值的数组初始化priority_queue对象。 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). 我知道我可以一个接一个地插入它们,但这将花费O(nlogn),而一次全部传递它们是O(n)。

The range constructor for std::priority_queue allows you to pass a comparator function in as an optional argument: std::priority_queue的范围构造函数允许您将比较器函数作为可选参数传入:

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. 在下面的示例中, std::greater<int>是比较函数,而myints是整数数组。 We can create a priority_queue my_priority_queue as follows: 我们可以如下创建一个priority_queue my_priority_queue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM