Source of stack03.cpp


  1: //stack03.cpp

  3: #include <iostream>
  4: #include <iomanip>
  5: #include <stack>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the assignment of one stack "
 11:         "to another,\nand the comparison of stacks.";
 12:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 14:     stack<int> s1;
 15:     s1.push(1);
 16:     s1.push(2);
 17:     s1.push(3);
 18:     s1.push(4);
 19:     cout << "\nThe stack s1 contains " << s1.size() << " values.";
 20:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 22:     cout << "\nNow we create three new empty stacks-s2, s3, s4-"
 23:         "and assign s1 to all three.\nThen we display the contents of "
 24:         "s1 to show what s2, s3 and s4 all contain.\nNote that the "
 25:         "process of displaying the values in s1 empties s1.";
 26:     stack<int> s2, s3, s4;
 27:     s4 = s3 = s2 = s1;
 28:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

 40:     cout << "\nNext we display the contents of s2 to confirm that "
 41:         "s1 did get assigned to s2.";
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     cout << "\nHere are the values of s2, in \"LIFO\" order:\n";
 45:     while(!s2.empty())
 46:     {
 47:         cout << "Popping: ";
 48:         cout << s2.top() << "\n";
 49:         s2.pop();
 50:     }
 51:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 53:     cout << "\nFinallly, we push the value 5 onto s4, and then we "
 54:         "output the result of\ncomparing s3 and s4 using each of the "
 55:         "relational operators.";
 56:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 58:     s4.push(5);
 59:     cout << "\ns3 == s4 is " << boolalpha << (s3 == s4) << ".";
 60:     cout << "\ns3 != s4 is " << boolalpha << (s3 != s4) << ".";
 61:     cout << "\ns3 <  s4 is " << boolalpha << (s3 <  s4) << ".";
 62:     cout << "\ns3 <= s4 is " << boolalpha << (s3 <= s4) << ".";
 63:     cout << "\ns3 >  s4 is " << boolalpha << (s3 >  s4) << ".";
 64:     cout << "\ns3 >= s4 is " << boolalpha << (s3 >= s4) << ".";
 65:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 66: }