C++ STL stack, pop(), push(), size() and top() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info:
To do: Using the C++ pop() to remove the element from the top of the stack, push() to add an element to the top of the stack, top() to return a reference to an element at the top of the stack and size() to return the number of elements in the stack in C++ programming
To show: How to use the C++ pop() to remove the element from the top of the stack, push() to add an element to the top of the stack, top() to return a reference to an element at the top of the stack and size() to return the number of elements in the stack in C++ programming
// C++ STL stack, pop(), push(), size() and top()
#include <stack>
#include <iostream>
using namespace std;
int main(void)
{
stack <int> st1, st2;
int j;
// push data element on the stack
cout<<"Pushing data into stack..."<<endl;
st1.push(21);
j = st1.top();
cout<<j<<' ';
st1.push(9);
j = st1.top();
cout<<j<<' ';
st1.push(12);
j = st1.top();
cout<<j<<' ';
st1.push(31);
j = st1.top();
cout<<j<<' '<<endl;
stack <int>::size_type i;
i = st1.size();
// print some data
cout<<"The stack length is "<<i<<endl;
i = st1.top();
cout<<"The element at the top of the stack is "<<i<<endl;
st1.pop();
i = st1.size();
cout<<"After a pop, the stack length is "<<i<<endl;
i = st1.top();
cout<<"After a pop, the element at the top of the stack is "<<i<<endl;
return 0;
}
Output examples:
Pushing data into stack...
21 9 12 31
The stack length is 4
The element at the top of the stack is 31
After a pop, the stack length is 3
After a pop, the element at the top of the stack is 12
Press any key to continue . . .