C++ 棧庫 - push() 函式



描述

C++ 函式 std::stack::push() 在棧頂插入新元素,並將棧的大小增加一。

宣告

以下是來自 std::stack 標頭檔案的 std::stack::push() 函式的宣告。

C++98

void push (const value_type& val);

C++11

void push (const value_type& val);

引數

val − 要分配給新插入元素的值。

返回值

無。

異常

取決於底層容器。

時間複雜度

常數,即 O(1)

示例

以下示例演示了 std::stack::push() 函式的使用。

#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   for (int i = 0; i < 5; ++i)
      s.push(i + 1);

   cout << "Stack contents are" << endl;

   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }

   return 0;
}

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

Stack contents are
5
4
3
2
1
stack.htm
廣告