STL__stack&&queue

stack

基本用法

push入栈一个元素

pop 出栈一个元素,但是不返回数

top 取栈顶元素

size 查看元素个数

empty 检查栈是否为空   (!empty()  栈不为空)

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<int> S;  //不可以带参构造,例如stack<int> S(3)、stack<int> S(3,3);
    //传数
    S.push(2);
    S.push(3);
    
    //查看元素个数
    //cout<<S.size()<<endl;

    //取数
    cout<<S.top()<<endl;
    cout<<S.top()<<endl; //输出俩都是3
    S.top();
    cout<<S.top()<<endl; //输出是2
    
    return 0;
}

进制转换 (会用到stack)

#include <iostream>
#include <stack>

using namespace std;

int itob(int decimal)
{
    stack<int> s;
    int res=0;
    while(decimal!=0)
    {
        s.push(decimal%2);
        decimal/=2;
    }
    while(!s.empty())  //队列不为空
    {
        res=res*10+s.top();
        s.pop();
    }
    return res;

}

int main()
{
    stack<int> S; 

    //把10进制转换为2进制
    int decimal=20;    //假设10进制的数是20
    cout<<itob(decimal);

    return 0;
}

逆序单词(拓展sstream,stoi,itoa)

输入一行字符串,将字符串逆序打印

输入:hello world my name is abc

输出:abc is name my world hello 

#include <iostream>
#include <stack>
#include <sstream>

using namespace std;

int main()
{
    string str;
    getline(cin,str);
    stringstream ss;
    ss<<str;   //把str一行的字符串流进去
    while(ss>>str)   //当str流出
    {
        S.push(str);
    }
    while(!S.empty())
    {
        cout<<S.top();
        S.pop();
        if(S.size()!=0)
        cout<<" ";
    }
    return 0;
   
}

 

字符串转数字

方法1:

#include <iostream>
#include <stack>
#include <sstream>

using namespace std;

int main()
{
    string s="1234";
    int i;
    stringstream ss;
    ss<<s;
    ss>>i;
    cout<<i;   //输出1234
    return 0;
   
}

方法2:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s="1234";
    int i=stoi(s);
    cout<<i;
    return 0;
   
}

数字转字符串

方法1:

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int a=1234;
    string out;
    stringstream ss;
    ss<<a;
    ss>>out;
    cout<<out<<endl;  //输出1234
    return 0;
   
}

方法2:(c++11)

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int a=1234;
    cout<<to_string(a)<<endl;
    return 0;
   
}

queue

push 

pop

front

size

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    queue<int> Q;
    Q.push(5);
    Q.push(6);
    cout<<Q.front()<<endl;  //输出队首元素
    Q.pop();    //弹出元素
    cout<<Q.front()<<endl;
    cout<<Q.size()<<endl;
    return 0;
   
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值