fork download
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7. cout << "Create stack containing values of type int" << endl;
  8. // We can create empty stack writing: stack<elements_type> variable_name;
  9. stack<int> st;
  10.  
  11. // To get current size of the stack (number of elements in it) we use "size" method
  12. cout << "Size of the stack: " << st.size() << endl;
  13.  
  14. cout << endl << "Add new elements to top of the stack" << endl;
  15. // To add new elements to the stack we use "push" method
  16. // This places new element passed as a parameter at the top of the stack
  17. st.push(5);
  18. st.push(-50);
  19. st.push(25);
  20.  
  21. cout << "Size of the stack: " << st.size() << endl;
  22.  
  23. // To get value of the top element in the stack we use "top" method
  24. // This method does not remove element from the stack
  25. cout << endl << "Top element of the stack: " << st.top() << endl;
  26. cout << "Removing top element from the stack" << endl;
  27. // To remove top element of the stack (last added) we use "pop" method
  28. // This method only removes the top element without returning its value
  29. st.pop();
  30. cout << "Top element of the stack: " << st.top() << endl;
  31. cout << "Size of the stack: " << st.size() << endl;
  32.  
  33. cout << endl << "Clearing stack by assigning new value to it" << endl;
  34. st = stack<int>();
  35.  
  36. cout << "Size of the stack: " << st.size() << endl;
  37.  
  38. cout << endl << "Checking if stack is empty" << endl;
  39. // To check if stack is empty (its size is equal to zero) we can use "empty" method
  40. // This method returns true if stack is empty, false otherwise
  41. if (st.empty()) {
  42. cout << "Stack is empty" << endl;
  43. } else {
  44. cout << "Stack is not empty" << endl;
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 5456KB
stdin
Standard input is empty
stdout
Create stack containing values of type int
Size of the stack: 0

Add new elements to top of the stack
Size of the stack: 3

Top element of the stack: 25
Removing top element from the stack
Top element of the stack: -50
Size of the stack: 2

Clearing stack by assigning new value to it
Size of the stack: 0

Checking if stack is empty
Stack is empty