无涯教程-C++ Stack - empty函数

72 阅读1分钟

C++ Stack empty()函数用于测试集合是否为空。在许多情况下,程序员在从堆栈中提取实际元素之前,会优先检查堆栈是否确实包含某些元素。这样做在存储和成本方面是有利的。

empty - 语法

bool empty() const;

empty - 参数

没有参数。由于该函数仅用于测试目的,因此它直接应用于堆栈。因此,不会传递任何参数。

empty - 返回值

如果引用的集合为空,则该方法返回" true",否则返回" false"。该方法仅用于测试目的,因此将根据测试结果返回值。

empty - 例子1

//下面给出的程序用于检测集合的空度。

#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

empty - 例子2

//下面给出的程序用于检测集合的空度。

#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

参考链接

www.learnfk.com/c++/cpp-sta…