fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. template <class T>
  5. struct PQ {
  6. vector<T> v;
  7. function<bool(const T&, const T&)> comp;
  8.  
  9. PQ() : comp(less<T>()) {}
  10.  
  11. void push(const T& value) {
  12. v.push_back(value);
  13. push_heap(v.begin(), v.end(), comp);
  14. }
  15.  
  16. void pop() {
  17. pop_heap(v.begin(), v.end(), comp);
  18. v.pop_back();
  19. }
  20.  
  21. const T& top() {
  22. return v.front();
  23. }
  24.  
  25. bool empty() {
  26. return v.empty();
  27. }
  28.  
  29. void change_comparator(function<bool(const T&, const T&)> other_comp) {
  30. comp = other_comp;
  31. make_heap(v.begin(), v.end(), comp);
  32. }
  33. };
  34.  
  35. template <class T>
  36. void print(PQ<T> pq) {
  37. while (!pq.empty()) {
  38. cout << pq.top() << " ";
  39. pq.pop();
  40. }
  41. cout << "\n";
  42. }
  43.  
  44. int main() {
  45. ios::sync_with_stdio(false);
  46. cin.tie(0);
  47. PQ<int> pq;
  48. for (int i = 1; i <= 10; ++i) {
  49. pq.push(i);
  50. }
  51. print(pq);
  52. pq.change_comparator(greater<int>());
  53. print(pq);
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 5524KB
stdin
Standard input is empty
stdout
10 9 8 7 6 5 4 3 2 1 
1 2 3 4 5 6 7 8 9 10