C++ STL 中的棧 (3.5)
在 C++ STL 中,棧用作容器,其實現為 LIFO 結構。LIFO 表示後進先出。可以將棧想象成一堆書,書一本疊在一本上面,最後放入的書將首先被移除,這就是為什麼它被稱為 LIFO 結構。
與棧相關的操作有:
top() - 此函式返回對棧頂元素的引用。
語法 - name_of_stack.top()
引數 - 無引數
返回值 - 對棧容器頂端元素的引用
push() - 此函式用於將元素插入到棧容器中。
語法 - name_of_stack.push(element)
引數 - 此函式接受要插入的元素。
返回值 - 它不返回任何值。
pop() - 此函式用於從棧容器中移除元素。
語法 - name_of_stack.pop()
引數 - 無引數
返回值 - 它移除棧頂元素並返回它。
size() - 此函式用於計算棧中存在的元素總數。
語法 - name_of_stack.size()
引數 - 無引數
返回值 - 它返回棧中元素的數量。
empty() - 此函式用於檢查棧是否為空。
語法 - name_of_stack.empty()
引數 - 無引數
返回值 - 它返回布林值 true 或 false。棧為空時為 true,棧不為空時為 false。
示例
#include <bits/stdc++.h> using namespace std; int main(){ //create a stack container stack <int> newStack; //insert elements to a stack newStack.push(10); newStack.push(20); newStack.push(30); newStack.push(40); //check whether the values are pushed in stack or not //using empty() if(!newStack.empty()){ //calculate size of a stack cout<<"Stack size is: "<< newStack.size(); } else{ cout<<"Stack is empty"; } cout<<"\nElements in the stack are:"; while(!newStack.empty()){ cout<<" "<< newStack.top(); newStack.pop(); } return 0; }
輸出
Stack size is: 4 Elements in the stack are: 40 30 20 10
廣告