Source of priority_queue01.cpp


  1: //priority_queue01.cpp

  3: #include <iostream>
  4: #include <queue>
  5: using namespace std;

  7: int main()
  8: {
  9:     cout << "\nThis program illustrates a simple priority queue of "
 10:         "integers, including a\ndefault constructor, a copy constructor, "
 11:         "and the push(), pop(), top(), empty()\nand size() member "
 12:         "functions of the STL priority_queue interface.";
 13:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 15:     priority_queue<int> pq1;
 16:     pq1.push(19);
 17:     pq1.push(35);
 18:     pq1.push(46);
 19:     pq1.push(11);
 20:     pq1.push(27);

 22:     //Make a copy of pq1 for later use, before destroying
 23:     //pq1 when its values are displayed.
 24:     priority_queue<int> pq2(pq1);

 26:     cout << "\nThe priority queue pq1 contains "
 27:          << pq1.size() << " elements.";
 28:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 30:     cout << "\nHere they are, in priority order:\n";
 31:     //This is the proper way to access the elements of a priority queue:
 32:     while(!pq1.empty())
 33:     {
 34:         cout << "Popping: ";
 35:         cout << pq1.top() << "\n";
 36:         pq1.pop();
 37:     }
 38:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 40:     cout << "\nBefore displaying the contents of the priority queue "
 41:         "pq2, which was a copy\nof pq1, we add to it the values 75 and "
 42:         "5, in that order.";
 43:     pq2.push(75);
 44:     pq2.push(5);
 45:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 47:     cout << "\nNow here are the new contents of pq2, in priority order:\n";
 48:     while(!pq2.empty())
 49:     {
 50:         cout << "Popping: ";
 51:         cout << pq2.top() << "\n";
 52:         pq2.pop();
 53:     }
 54:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 55: }