当前位置: 移动技术网 > IT编程>开发语言>C/C++ > STL之stack

STL之stack

2020年04月07日  | 移动技术网IT编程  | 我要评论

美国著名电影公司,河北二本院校,金马岛战役

stack即栈,一种先进后出的数据结构。

这次会在stack的基础上讲两个实际应用,以及讲一下stringstream。

直接上代码!

1、stack基础

#include<iostream>
#include<stack>
using namespace std;

int main()
{
    //构造
    stack<int> s; //一般空参构造

    //入栈
    s.push(2);
    s.push(6);
    s.push(8);
    cout << s.size() << endl; //size:3
    //stack不能遍历,只能一个一个退栈
    while (!s.empty()) { //输出8 6 2 先进后出
        cout << s.top() << ' '; //取栈顶,不会退栈
        s.pop(); //退栈,无返回值
    }
    cout << endl << s.size() << endl; //size:0
    return 0;
}

2、进制转换

#include<iostream>
#include<stack>
using namespace std;

int main()
{
    //进制转换10->2
    stack<int> s;
    int n;
    cin >> n;
    while (n) {
        s.push(n % 2);
        n /= 2;
    }
    while (!s.empty()) {
        n = n * 10 + s.top();
        s.pop();
    }
    cout << n << endl;
    return 0;
}

3、以空格分割的字符串逆序输出

#include<iostream>
#include<stack>
#include<string>
#include<sstream>
using namespace std;

int main()
{
    //以空格分割的字符串逆序输出
    string str;
    stack<string> s;
    getline(cin, str); //输入一行字符串
    stringstream ss; //stringstream常用于string类型转其他类型和切分以空格分割的字符串,头文件<sstream>
    ss << str;
    while (ss >> str)
        s.push(str);
    while (!s.empty()) {
        cout << s.top();
        s.pop();
        if (s.size() != 0)
            cout << ' ';
    }
    cout << endl;
    return 0;
}

4、string类型转换

#include<iostream>
#include<stack>
#include<string>
#include<sstream>
using namespace std;

int main()
{
    //字符串转int/double,使用stringstream
    int intval;
    double douval;
    stringstream ss;
    string str1 = "268";
    string str2 = "268.369";
    ss << str1;
    ss >> intval;
    ss.clear(); //一定要clear
    ss << str2;
    ss >> douval;
    cout << double(intval + douval) << endl;

    //字符串类型与int类型之间的转换,使用函数
    int n = stoi(str1);
    cout << 2 * n << endl;
    string str3 = to_string(n);
    cout << str1 + str3 << endl;
    return 0;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网