我在 http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/ 上找到了 priority_queue 的构造函数是这样的:
priority_queue (const Compare& comp, const Container& ctnr);
但是我找到的例子是这样的:
std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
这两个构造函数有什么区别?
这两个我都自己试过了,但是第一个不行,priority_queue没有从小到大排序。这是代码:
priority_queue<greater<int>, vector<int>> pq;
pq.push(4);
pq.push(2);
pq.push(1);
pq.push(3);
pq.push(5);
for (int i = 0; i < 5; i++) {
cout << pq.top() << endl;
pq.pop();
}
结果还是5,4,3,2,1
最佳答案
What's the difference between these two constructors?
其中一个是构造函数;另一个不是。
以 typedef
开头的行只是创建了一个类型别名,称为 mypq_type
。当您创建此 mypq_type
类型的对象时,您仍然会传递那些相同的构造函数参数。
关于C++优先级队列构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41389851/