C++ STL 中的 list empty() 函数

c++server side programmingprogramming

本文将讨论 C++ 中 list::empty() 函数的工作原理、语法和示例。

STL 中的 List 是什么?

List 是一种数据结构,允许在任意位置以恒定时间顺序插入和删除元素。List 实现为双向链表。List 允许非连续的内存分配。List 在插入、提取和在容器中任意位置移动元素方面比数组、向量和双端队列表现更好。在 List 中,直接访问元素速度较慢,并且 List 与 forward_list 类似,但 Forward List 对象是单链表,只能向前迭代。

什么是 list::empty()?

list::empty() 是 C++ STL 中的一个内置函数,在头文件中声明。 list::empty() 检查给定列表容器是否为空(大小为 0)。如果列表为空,则返回 true;如果列表不为空,则返回 false。

语法

bool list_name.empty();

此函数不接受任何值。

返回值

如果容器大小为零,则此函数返回 true;如果容器大小不为零,则返回 false。

示例

在下面的代码中,我们将调用函数 empty() 来检查列表是否为空;如果列表为空,则我们将使用 push_back() 函数向列表中插入元素以检查结果。

#include <bits/stdc++.h>
using namespace std;
int main() {
   list<int> myList; //to create a list
   //调用 empty() 函数检查列表是否为空
   if (myList.empty())
      cout << "my list is empty\n";
   else
      cout << "my list isn’t empty\n";
   //push_back() 用于在列表中插入元素
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   myList.push_back(4);
   if (myList.empty())
      cout << "my list is empty\n";
   else
      cout << "my list is not empty\n";
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出

my list is empty
my list is not empty

在下面的代码中,我们尝试将 1-10 之间的数字相乘,然后减去 1。

  • 首先使用 push_back() 函数将元素插入列表

  • 使用 empty() 函数遍历列表,直到它不再为空。

  • 打印结果

示例

#include <bits/stdc++.h> 
using namespace std;
int main (){
   list<int> myList;
   int product = 0;
   for (int i=1;i<=10;++i)
   mylist.push_back(i);
   while (!mylist.empty()){
      product *= myList.front();
      myList.pop_front();
   }
   cout << "product of numbers from 1-10 is: " <<product << '\n';
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出

product of numbers from 1-10 is: 3628800

相关文章