C++ Stack 库 - size() 函数
描述
C++ 函数 std::stack::size() 返回堆栈中存在的元素总数。
声明
以下是 std::stack::size() 函数形式 std::stack 头的声明。
C++98
size_type size() const;
参数
None
返回值
返回堆栈中存在的元素数。
异常
取决于底层容器。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 std::stack::size() 函数的用法。
#include <iostream>
#include <stack>
using namespace std;
int main(void) {
stack<int> s;
cout << "Initial size of stack = " << s.size() << endl;
for (int i = 0; i < 5; ++i)
s.push(i + 1);
cout << "Stack size after push operation = " << s.size() << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Initial size of stack = 0 Stack size after push operation = 5

