C++ STL 中的棧頂()


在本文中,我們將討論 C++ STL 中 stack::top() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的堆疊?

堆疊是一種以 LIFO(後進先出)方式儲存資料的程式碼結構,在其中,我們在插入最後一個元素的頂部進行插入和刪除。就像一沓盤子,如果我們想將一個新盤子壓入堆疊,我們從頂部插入;如果我們想從堆疊中移出盤子,我們也從頂部移出。

什麼是 stack::top()?

stack::top() 函式是 C++ STL 中的一個內建函式,在 <stack> 標頭檔案中定義。top() 用於訪問堆疊容器頂部的元素。在一個堆疊中,頂元素是最後插入或最近插入的元素。

語法

stack_name.top();

引數

該函式不接受任何引數−

返回值

此函式返回堆疊容器頂部元素的引用。

輸入 

std::stack<int> odd;
odd.emplace(1);
odd.emplace(3);
odd.emplace(5);
odd.top();

輸出

5

示例

 即時演示

#include <iostream>
#include <stack&lgt;
using namespace std;
int main(){
   stack<int> stck_1, stck_2;
   //inserting elements to stack 1
   stck_1.push(1);
   stck_1.push(2);
   stck_1.push(3);
   stck_1.push(4);
   //swapping elements of stack 1 in stack 2 and vice-versa
   cout<<"The top element in stack using TOP(): "<<stck_1.top();
   cout<<"\nElements in stack are: ";
   while (!stck_1.empty()){
      cout<<stck_1.top()<<" ";
      stck_1.pop();
   }
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出−

The top element in stack using TOP(): 4
Elements in stack are: 4 3 2 1

更新於: 2020 年 4 月 22 日

7K+ 瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.