cpp 栈为空
时间: 2023-12-17 07:12:45 浏览: 26
在C++中,我们可以通过empty()函数来判断一个stack是否为空。empty()函数返回一个bool值,如果栈为空,返回true,否则返回false。
以下是一个示例代码,演示了如何判断一个栈是否为空:
```cpp
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
// 判断栈是否为空
if (s.empty()) {
cout << "Stack is empty" << endl;
} else {
cout << "Stack is not empty" << endl;
}
// 将元素入栈
s.push(1);
s.push(2);
s.push(3);
// 再次判断栈是否为空
if (s.empty()) {
cout << "Stack is empty" << endl;
} else {
cout << "Stack is not empty" << endl;
}
return 0;
}
```
输出结果如下:
```
Stack is empty
Stack is not empty
```
可以看到,当栈为空时,empty()函数返回true,否则返回false。在实际编程中,我们可以利用empty()函数来判断栈是否为空,从而避免在空栈中执行pop()等操作导致的错误。