C++ Stack 库 - push() 函数
描述
C++ 函数 std::stack::push() 通过执行移动操作在栈顶插入新元素。 此操作将堆栈大小增加一。
声明
以下是 std::stack::push() 函数形式 std::stack 头的声明。
C++11
void push (value_type&& val);
参数
val − 要分配给新插入元素的值。
返回值
None.
异常
取决于底层容器。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 std::stack::push() 函数的用法。
#include <iostream>
#include <stack>
using namespace std;
int main(void) {
stack<int> s1;
stack<int> s2;
for (int i = 0; i < 5; ++i)
s1.push(i + 1);
while (!s1.empty()) {
s2.push(move(s1.top()));
s1.pop();
}
cout << "Stack contents are" << endl;
while (!s2.empty()) {
cout << s2.top() << endl;
s2.pop();
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Stack contents are 1 2 3 4 5

