Or login with:
#include<stack> namespace std { template <class T, class Container = deque<T>> class stack; }
stack<int> IntStack; // creates a stack of integer type
Another short example illustrates the methods size() and empty():
#include <iostream> #include <stack> #include <conio.h> using namespace std; int main() { stack<char> codes; codes.push('a'); codes.push('b'); cout<<"The size of the stack is:"<<codes.size<<endl; // checking if the stack is empty if(codes.empty()==true) cout<<"The Stack is Empty"; // prints the size of the stack _getch(); return 0; }The output of this program will be 2 since there are 2 elements in the stack.
| Operation | Effect |
|---|---|
| stack< El > c | Creates an empty stack c which can hold values of type El |
| stack< El > c1(c2) | Creates c1 as a copy of c2, whose component type must be El |
| stack< El > c1=c2 | Copy constructor (alternate usage syntax) |
| Operation | Effect |
|---|---|
| c1==c2 | Returns if c1 is equal to c2 |
| c1!=c2 | Returns if c1 is not equal to c2 (equivalent to !(c1==c2)) |
| c1<c2 | Returns if c1 is less than c2 |
| c1<=c2 | Returns if c1 is less than or equal to c2 (equivalent to !(c2<c1)) |
| c1>c2 | Returns if c1 is greater than c2 (equivalent to c2<c1) |
| c1>=c2 | Returns if c1 is greater than or equal to c2 (equivalent to !(c1<c2)) |
| c.top() | Returns a reference (or const_reference) to the top component of c |
| c.size() | Returns a value of type size_type giving the number of values currently in c |
| c.empty() | Returns true if c is empty (contains zero values); otherwise returns false |
| Operation | Effect |
|---|---|
| c1=c2 | Assigns c2 to c1, and return the common value. The stack on the left of an assignment receives the values and size of the one on the right |
| c.push(val) | Adds val to the top of c, increasing the size of c by one |
| c.pop() | Removes the top value of c, decreasing the size of c by one |
#include <iostream> #include <stack> using namespace std; int main() { int data[] = {41, 38, 53, 20, 78, 52, 69}; stack<int> s; cout << "The stack size is now " << s.size() << endl; cout << "Pushing 4 elements " << endl; for (int i = 0; i < 4; ++i) s.push(thedata[i]); cout << "The stack size is now " << s.size() << endl; cout << "Popping 3 elements " << endl; for (int i = 0; i < 3; ++i) { cout << s.top() << endl; s.pop(); } cout << "The stack size is now " << s.size() << endl; return 0; }
You must login to leave a messge