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 << "结果是: " << sum;
return 0;
}
return 0;
}
输出:
结果是: 55
//下面给出的程序用于检测容器是否为空。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
std::stack<int> newstack;
newstack.push(69);
//检查堆栈是否为空
if(newstack.empty())
{
cout<<"堆栈为空,插入一些元素以继续前进";
}
else
{
cout<<"元素出现在堆栈中";
}
return 0;
}
输出:
元素出现在堆栈中
该函数仅用于检测容器是否为空,因此不接受任何参数并且具有恒定的复杂性。
仅访问容器。访问堆栈以检查元素的存在。并非所有元素都可以通过此函数访问,但是可以一眼检查一下容器是否为空或是否存在。
提供了与在底层容器对象上执行的操作相同的保证。