fork download
  1. #include <iostream>
  2.  
  3. class Item{
  4. private:
  5. int key;
  6. int data;
  7. public:
  8. Item(): data(0), key(0){}
  9. Item(int data, int key): data(data), key(key){}
  10. void print(){
  11. std::cout << "data: " << data << ", key " << key << std::endl;
  12. }
  13. bool operator <(const Item &item){ return key < item.key; }
  14. bool operator >(const Item &item){ return key > item.key; }
  15. };
  16.  
  17. template<class Item>
  18. class PQ{
  19. private:
  20. Item *pq; /*Массив элементов*/
  21. int n; /*Текущее оличество элементов в очереди*/
  22. public:
  23. PQ(int max){
  24. pq = new Item[max];
  25. n = 0;
  26. }
  27.  
  28. int empty() const{ return n == 0; }
  29.  
  30. void insert(Item item){
  31. int location = n - 1;
  32.  
  33. while(location >= 0 && pq[location] > item){
  34. pq[location + 1] = pq[location];
  35. location = location - 1;
  36. }
  37. pq[location + 1] = item;
  38. //pq[n++] = item;
  39. }
  40.  
  41. Item getmax(){
  42. int max = 0;
  43.  
  44. for(int i = 1; i < n; i++)
  45. if(pq[max] < pq[i])
  46. max = i;
  47. std::swap(pq[max], pq[n-1]);
  48. return pq[--n];
  49. }
  50.  
  51. Item getmin(){
  52. int min = 0;
  53.  
  54. for(int i = 1; i < n; i++)
  55. if(pq[min] > pq[i])
  56. min = i;
  57. std::swap(pq[min], pq[n-1]);
  58. return pq[--n];
  59. }
  60.  
  61. void show(){
  62. for(int i = 0; i < n; i++)
  63. pq[i].print();
  64. }
  65. };
  66.  
  67. int main(){
  68. int p;;
  69. PQ<Item> pq(50);
  70.  
  71. for(int i = 0; i < 10; i++)
  72. pq.insert(Item(7, i));
  73.  
  74. pq.show();
  75.  
  76. std::cout << "max: ";
  77. pq.getmax().print();
  78. std::cout << "max: ";
  79. pq.getmax().print();
  80. std::cout << "min: ";
  81. pq.getmin().print();
  82. std::cout << "min: ";
  83. pq.getmin().print();
  84.  
  85. std::cin >> p;
  86. return 0;
  87. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
max: data: 7, key 9
max: data: 409, key 0
min: data: 0, key 0
min: data: 0, key 0