C++ STL栈Stack的使用
生活随笔
收集整理的這篇文章主要介紹了
C++ STL栈Stack的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++ STL stack 用法
Stack(棧)是一種后進先出的數據結構,也就是LIFO(last in first out) ,最后加入棧的元素將最先被取出來,在棧的同一端進行數據的插入與取出,這一段叫做“棧頂”。
使用STL的stack,需要頭文件#include<stack>
最常見,也是最簡單的定義方式: stack <int> mystack; //構造一個用于存放int類型的空棧
棧的清空
while (!s.empty()){cout << s.top() << "\n";s.pop();}其他函數
s.push(10);入棧
s.pop();出棧
empty(); 堆棧為空則返回真
size(); 返回棧中元素數目
top(); 返回棧頂元素
代碼實例
一道拆括號的練習題
#include<iostream> #include<string> #include<stack> using namespace std;int main() {int total;cin >> total;stack<char> stackStr;string str;int j;for (j = 0; j < total; j++){cin >> str;int i;while (!stackStr.empty())//清空棧{stackStr.pop();}for (i = 0; i < str.length(); i++){if (str[i] == 'G'){cout << stackStr.size() << endl;break;}else{if (stackStr.size() == 0)//棧為空{stackStr.push(str[i]);//入棧}else if (stackStr.top() == '['&&str[i] == ']')//匹配{stackStr.pop();//出棧}else{stackStr.push(str[i]);//入棧}}}}cout << endl;system("pause"); }總結
以上是生活随笔為你收集整理的C++ STL栈Stack的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ACM练习 愚人节拆括号【vector的
- 下一篇: 【C++鼠标键盘操作】自动下载CSDN博