C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ Stack empty()

C++ Stack empty()函数

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

语法

bool empty() const;

参数

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

返回值

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

示例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

示例2

//下面给出的程序用于检测容器的空度。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
    std::stack<int> newstack;
    newstack.push(69);
    //Checking whether the stack is empty
    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

复杂度

该功能仅用于检测容器的空度,因此不接受任何参数,并且具有恒定的复杂性。

数据竞争

仅可访问容器。访问堆栈以检查元素的存在。并非所有的元素都可以通过此函数访问,但是可以一眼检查一下容器是否完全为空或是否存在。

异常安全性

保证为提供与在基础容器对象上执行的操作等效的操作。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4