一.栈
用来保存数据,遵循先进后出的原则。
头文件:#include <stack> 声明一个栈 stack<int>s 声明存储int 类型数据的栈s
#include <iostream> #include <stack> using namespace std; int main() { stack<int>s; cout<<"向栈中插入数据1,2,3"<<endl; s.push(1);//s={1} s.push(2);//s={1,2} s.push(3);//s={1,2,3}; cout<<"栈顶数据为: "<<s.top()<<endl; s.pop();//删除栈顶元素 cout<<"原来的栈顶数据删除后,新的栈顶数据为: "<<s.top()<<endl; s.pop(); cout<<"原来的栈顶数据删除后,新的栈顶数据为: "<<s.top()<<endl; s.pop(); //以下代码和上面执行相同的功能 for(int i=1;i<=3;i++) s.push(i); while(!s.empty()) //empty()这个函数来判断栈中是否元素为空 { cout<<s.top()<<endl; s.pop(); } return 0; }
执行结果:
因为后进先出的元素,所以栈用来进制转换很方便
下面例子是将一个十进制数字转化为2进制数保存在栈中,再从栈中输出。
#include <iostream> #include <stack> using namespace std; int main() { int m; while(cin>>m) { stack<int>s; while(!s.empty())//现判断一下栈中元素是否为空 s.pop(); while(m!=0) { s.push(m%2); m/=2; } while(!s.empty()) { cout<<s.top();//依次输出栈顶元素 s.pop(); } cout<<endl; } return 0; }
运行结果: