C++ Stack::top() 函式



C++ 函式std::stack::top()返回棧頂元素。在棧中,棧頂元素是最後插入或最近插入的元素,因為棧是後進先出 (LIFO) 容器。我們需要執行彈出操作才能連續從棧中獲取棧頂元素。

top() 函式不接受任何引數。此外,重要的是要確保不能在空棧上呼叫 top() 函式,如果嘗試這樣做,它將丟擲異常。

語法

以下是 std::stack::top() 函式的語法:

stack_name.top()

引數

此函式不接受任何引數。

返回值

返回棧頂元素。

示例 1

以下示例顯示了 std::stack::top() 函式的用法。在這裡,我們建立一個空的整數棧,並使用 emplace() 函式向其中插入五個元素。然後,我們使用 top() 和 pop() 函式分別以 LIFO 順序檢索和移除元素,直到棧變空。

#include <iostream>
#include <stack>
using namespace std;

int main(void) {
   stack<int> s;
   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);
   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }
   return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

5
4
3
2
1

示例 2

在下面的示例中,我們建立一個棧 's' 並向棧中插入三個整數值。然後,我們使用 top() 函式檢索棧頂元素:

#include <iostream>
#include <stack>
using namespace std;

int main(){
   stack<int> s;
   s.push(7);
   s.push(32);
   s.push(95);
   cout << "The top element in s1 is:" << endl;
   cout << s.top();
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

The top element in s1 is:
95

示例 3

在這裡,我們建立一個整數棧 's' 並向棧中插入兩個值 (3 和 5)。然後,我們使用 top() 函式將棧頂元素修改為 '7'。

#include <iostream>
#include <stack>
using namespace std;

int main(){
   stack<int> s;
   s.push(3);
   s.push(5);
   s.top() = 7;
   cout << "Top element of the stack: " << s.top() << endl;
   return 0;
}

輸出

以下是上述程式碼的輸出:

Top element of the stack: 7

示例 4

現在,我們建立一個名為 s1 的空字元資料型別棧,並按順序向棧中插入字元 't'、'r'、'u'、'c' 和 'k'。然後,我們使用 top() 函式檢索棧頂元素:

#include <iostream>
#include <stack>
using namespace std;

int main(void) {
   stack <char> s1;
   s1.push('t');
   s1.push('r');
   s1.push('u');
   s1.push('c');
   s1.push('k');
   cout << "The top element in s1 is:" << endl;
   cout << s1.top();
   return 0;
}

輸出

上述程式碼的輸出如下:

The top element in s1 is:
k
廣告