堆棧是一種具有LIFO(後進先出)類型的容器適配器,其中在稱為堆棧頂部的一端添加了一個新元素,而僅從同一端刪除了一個元素。
stack::top()top()函數用於引用堆棧的top(或最新)元素。
用法:
stackname.top()
參數:無需傳遞任何值作為參數。
返回值:直接引用堆棧容器的頂部元素。
例子:
Input :stackname.push(5);
         stackname.push(1);
         stackname.top();
Output:1
Input :stackname.push(5);
         stackname.push(1);
         stackname.push(2);
         stackname.top();
Output:2
錯誤和異常
- 如果堆棧容器為空,則會導致未定義的行為
 - 如果堆棧不為空,則沒有異常拋出保證
 
// CPP program to illustrate 
// Implementation of top() function 
#include <iostream> 
#include <stack> 
using namespace std; 
  
int main() 
{ 
    stack<int> mystack; 
    mystack.push(5); 
    mystack.push(1); 
    mystack.push(2); 
  
    // Stack top 
    cout << mystack.top(); 
    return 0; 
}輸出:
2
應用:
給定一堆整數,找到所有整數的總和。
Input:1, 8, 3, 6, 2 Output:20
算法
- 檢查堆棧是否為空,如果不是,則將頂部元素添加到初始化為0的變量中,然後彈出頂部元素。
 - 重複此步驟,直到堆棧為空。
 - 打印變量的最終值。
 
// CPP program to illustrate 
// Application of top() function 
#include <iostream> 
#include <stack> 
using namespace std; 
  
int main() 
{ 
    int sum = 0; 
    stack<int> mystack; 
    mystack.push(1); 
    mystack.push(8); 
    mystack.push(3); 
    mystack.push(6); 
    mystack.push(2); 
  
    // Stack becomes 1, 8, 3, 6, 2 
  
    while (!mystack.empty()) { 
        sum = sum + mystack.top(); 
        mystack.pop(); 
    } 
    cout << sum; 
    return 0; 
}輸出:
20
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 stack top() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
