C++ STL之stack栈容器

一、STL:

1)标准模版库,提供了通用的模版库和函数。如:向量、链表、队列、栈。

2)核心组建包括:容器(Containers)、算法(Algorithms)、迭代器(Iterators)。

二、Stack栈容器:

1)容器适配器,遵循先进后出(FILO)数据结构。

2)头文件:#include <stack>

3)常用函数:

  • empty:判断堆栈元素是否为空,true表示栈元素为空;
  • pop:移除栈顶元素;
  • push:栈顶添加元素;
  • top:返回栈顶元素;
  • size:返回栈中元素数目;

三、题目描述:

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。 比如: (1) “hello xiao mi”-> “mi xiao hello”

四、题目链接:

https://www.nowcoder.com/practice/0ae4a12ab0a048ee900d1536a6e98315?tpId=85&&tqId=29896&rp=1&ru=/activity/oj&qru=/ta/2017test/question-ranking

五、答案解析:

#include<iostream>
#include<stack>
using namespace std;
int main(){
    string ss;
    stack<string> sstack;
    while(cin>>ss){
        sstack.push(ss);
    }
    while(sstack.size()>1){
        cout<<sstack.top()<<" ";
        sstack.pop();
    }
    cout<<sstack.top()<<endl;
    return 0;
}

六、参考:

http://www.runoob.com/cplusplus/cpp-stl-tutorial.html (C++ STL教程)

https://blog.csdn.net/l494926429/article/details/52066918 

https://blog.csdn.net/wallwind/article/details/6858634

猜你喜欢

转载自blog.csdn.net/u013096666/article/details/80738410