C++ Stack empty()函数用于测试集合是否为空。在许多情况下,程序员在从堆栈中提取实际元素之前,会优先检查堆栈是否确实包含某些元素。这样做在存储和成本方面是有利的。
bool empty() const;
没有参数。由于该函数仅用于测试目的,因此它直接应用于堆栈。因此,不会传递任何参数。
如果引用的集合为空,则该方法返回" true",否则返回" false"。该方法仅用于测试目的,因此将根据测试结果返回值。
//下面给出的程序用于检测集合的空度。
#include <iostream> #include <stack> int main() { std::stack<int> newstack; int sum=0; for (int j=1; j<=10; j++) newstack.push(j); while (!newstack.empty ()) { sum += newstack.top (); newstack.pop (); } std::cout << "Result is: " << sum; return 0; } return 0; }
输出:
Result is: 55
//下面给出的程序用于检测集合的空度。
#include <iostream> #include <stack> using namespace std; int main() { std::stack<int> newstack; newstack.push(69); //检查堆栈是否为空 if(newstack.empty()) { cout<<"The stack is empty, insert some elements to keep going"; } else { cout<<"Elements are present in the stack"; } return 0; }
输出:
Elements are present in the stack
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)