C++ Stack 库 - stack() 函数
描述
C++ 构造函数 std::stack::stack() 创建堆栈容器并将 ctnr 参数的副本分配给堆栈元素。 如果未提供 ctnr 参数,则它构造零元素的空堆栈。
声明
以下是 std::stack::stack() 构造函数形式 std::stack 头的声明。
C++98
explicit stack (const container_type& ctnr = container_type());
C++11
explicit stack (const container_type& ctnr);
参数
ctnr − 容器类型,是类模板的第二个参数。
返回值
构造函数从不返回值。
异常
此成员函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::stack::stack() 构造函数的用法。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main(void) {
stack<int> s1;
vector<int> v = {1, 2, 3, 4, 5};
stack<int, vector<int>> s2(v);
cout << "Size of stack s1 = " << s1.size() << endl;
cout << "Contents of stack s2" << endl;
while (!s2.empty()) {
cout << s2.top() << endl;
s2.pop();
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Size of stack s1 = 0 Contents of stack s2 5 4 3 2 1

