在 C++ 標準庫中,stack
類沒有直接提供一個成員函數來檢查棧是否為空
#include <iostream>
#include <stack>
int main() {
std::stack<int> myStack;
if (myStack.empty()) {
std::cout << "The stack is empty." << std::endl;
} else {
std::cout << "The stack is not empty." << std::endl;
}
return 0;
}
在這個示例中,我們創(chuàng)建了一個空的 std::stack<int>
對象,并使用 empty()
函數檢查它是否為空。如果棧為空,程序將輸出 “The stack is empty.”,否則將輸出 “The stack is not empty.”。