当心变量发生上溢或下溢,数组的下标越界。
1 #include <iostream> 2 #include <stack> 3 4 5 using namespace std ; 6 7 typedef stack<int> STACK_INT; 8 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 9 10 int main(int argc, char** argv) { 11 STACK_INT stack1; 12 int i; 13 14 //判断栈是否空 15 cout << "stack1.empty() returned " << 16 (stack1.empty()? "true": "false") << endl; 17 18 //0,2,4,6...入栈 19 for (i=0;i<10;i=i+2) 20 stack1.push(i); 21 22 //top()函数 23 if (!stack1.empty()) 24 cout << "stack1.top() returned " <<stack1.top() << endl; 25 26 //计算栈的长度 27 cout<<"stack1.size(): "<<stack1.size()<<endl; 28 29 //改变栈顶的值 20. 30 if (!stack1.empty()) { 31 cout << "stack1.top()=20;" << endl; 32 stack1.top()=20; 33 } 34 35 //弹出栈中所有的数据并显示 36 cout<<"stack1: "; 37 while (!stack1.empty()) { 38 cout<<stack1.top()<<" "; 39 stack1.pop(); 40 } 41 cout<<endl; 42 return 0; 43 }