- // 容器 stack, 其源代码包含着 deque, 其本质也可被称为容器的适配器
- // 容器 stcak 中不能进行定位插入或着删除, 因为一旦进行定位插入和删除, 那么栈这个容器的封闭性将会被破坏
- #include <iostream>
- #include <stack>
- using namespace std;
- int main()
- {
- stack<int> s;
- s.push(1);
- s.push(2);
- s.push(3);
- cout<<s.top()<<endl;
- s.pop();
- cout<<s.top()<<endl;
- return 0;
- }
- // 利用 stack 实现将十进制转换为二进制
- #include <iostream>
- #include <stack>
- using namespace std;
- int change(int decimal)
- {
- stack <int> s;
- int sum=0;
- while(decimal)
- {
- s.push(decimal%2);
- decimal/=2;
- }
- while(!s.empty())
- {
- sum=sum*10+s.top() ;
- s.pop();
- }
- return sum;
- }
- int main()
- {
- int a=2;
- cout<<change(a);
- return 0;
- }
- // 逆序单词
- #include <iostream>
- #include <stack>
- #include <sstream>
- using namespace std;
- int main()
- {
- string str;
- stack <string> s;
- getline(cin,str);
- stringstream ss;// 绑定一行字符串, 并以空格为分隔符将单词分开
- ss<<str;
- while(ss>>str)
- s.push(str);
- while(!s.empty())
- {
- cout<<s.top() ;
- s.pop();
- if(s.size())
- cout<<" ";
- }
- return 0;
- }
- // 字符串和数字之间的互相转化
- #include <iostream>
- #include <sstream>
- using namespace std;
- int main()
- {
- string s="1234";
- int i;
- stringstream ss;
- ss<<s;
- ss>>i;
- cout<<i;
- return 0;
- }
- // 字符串和数字之间的互相转化
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string s="1234";
- int i=stoi(s);
- cout<<i;
- return 0;
- }
- // 字符串和数字之间的互相转化
- // 将数字转化为字符串
- #include <iostream>
- #include <sstream>
- using namespace std;
- int main()
- {
- int a=1234;
- string out;
- stringstream ss;
- ss<<a;
- ss>>out;
- cout<<out<<endl;
- }
- // 字符串和数字之间的互相转化
- // 将数字转化为字符串
- //c++ 11 新更新
- #include <iostream>
- using namespace std;
- int main()
- {
- int a=1234;
- string s;
- s=to_string(a);
- cout<<s<<endl;
- return 0;
- }
来源: http://www.bubuko.com/infodetail-3412791.html