STL之stack

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;
}
posted @ 2020-04-07 10:04  你的名字_子集  阅读(299)  评论(0编辑  收藏  举报