priority_queue优先队列

A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take priority_queue优先队列 - 图1 time, and retrieval takes priority_queue优先队列 - 图2 time.

  1. priority_queue<int> q;
  2. q.push(3);
  3. q.push(5);
  4. q.push(7);
  5. q.push(2);
  6. cout << q.top() << "\n"; // 7
  7. q.pop();
  8. cout << q.top() << "\n"; // 5
  9. q.pop();
  10. q.push(6);
  11. cout << q.top() << "\n"; // 6
  12. q.pop();

默认是大根堆,如果要写小根堆,就是push x进去的时候,push成-x,取出使用的时候,加个负号再使用。实现大根堆,还有一个方法,如下:

  1. priority_queue<int,vector<int>,greater<int> >q;//这样就可以实现小根堆了

参考:https://www.cnblogs.com/zwfymqz/p/7800654.html, 如何实现自定义结构体的排序