在本文中,我们将讨论C ++ STL中list::empty()和list::size()函数的工作,语法和示例。
列表是允许在任何地方按顺序进行恒定时间插入和删除的容器。列表被实现为双链表。列表允许非连续的内存分配。与数组,向量和双端队列相比,列表在容器中的任何位置执行元素的插入提取和移动效果更好。在列表中,对元素的直接访问很慢,并且列表类似于forward_list,但是转发列表对象是单个链接列表,并且只能迭代转发。
list::empty()是C ++ STL中的内置函数,在头文件中声明。此函数用于检查列表容器是否为空(大小为0)。
List.name.empty()
如果列表为空,则返回布尔表达式True,如果不为空,则返回false。
Input List: 50 60 80 90 Output False Input List: Output True
首先,我们声明列表。
然后我们打印列表。
然后,我们声明empty()函数。
通过使用上述方法,我们可以检查列表为空。通过以上方法,我们可以在列表中输入非空列表中的元素。
// C++ code to demonstrate the working of list empty( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 55, 84, 38, 66, 67 };
   //打印列表
   cout<< “ List: “;
   for( auto x = List.begin( ); x != List.end( ); ++x)
   cout<< *x << “ “;
   //声明empty()函数
   If (lisy.empty( )){
      Cout<< “ True”;
   } else {
      cout<< “false”;
   }
   return 0;
}输出结果
如果我们运行上面的代码,那么它将生成以下输出
Input - List: 55 84 38 66 67 Output - false Input – List: Output – True
list::size()是C ++ STL中的内置函数,在头文件中声明。此功能用于查找列表的大小。通常,我们在列表中找到元素编号。
listname.size( )
返回-返回列表中元素的编号
Input – List: 5 6 7 8 9 10 Output – 6 Input – W O N D E R S Output – 7
首先,我们声明列表。
然后我们打印列表。
然后我们使用size()函数打印列表的大小。
通过使用上述方法,我们可以找到列表的大小。
// C++ code to demonstrate the working of list size( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main( ){
   List<char> list = { ‘M’, ‘A’, ‘R’, ‘C’, ‘H’, };
   cout<< " List: ";
   for( auto x = list.begin( ); x != list.end( ); ++x)
   cout<< *x << " ";
   //使用size()函数打印列表中的元素编号
   cout<< " Size of List" << list.size( );
   return 0;
}输出结果
如果我们运行上面的代码,那么它将生成以下输出
Input – List: M A R C H Output – Size of List: 5