C++ STL 中的 list_empty( ) 和 list_size( )
在本文中,我们将讨论 C++ STL 中 list::empty() 和 list::size() 函数的工作原理、语法和示例。
什么是 STL 中的 List?
List 是一种容器,允许在序列中的任何位置进行常数时间插入和删除。List 以双向链表的形式实现。List 允许非连续内存分配。与数组、向量和双端队列相比,List 在任何位置插入、提取和移动元素方面性能更好。在 List 中,直接访问元素速度较慢,并且 List 类似于 forward_list,但 forward_list 对象是单向链表,只能向前迭代。
什么是 list::empty( )?
list::empty() 是 C++ STL 中一个内置函数,在头文件中声明。此函数用于检查列表容器是否为空(大小为 0)。
语法
List.name.empty( )
返回值
如果列表为空,则返回布尔表达式 True,如果不为空,则返回 False。
示例
Input List: 50 60 80 90 Output False Input List: Output True
可以遵循的方法
首先我们声明 List。
然后我们打印 List。
然后我们声明 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 };
// print the list
cout<< “ List: “;
for( auto x = List.begin( ); x != List.end( ); ++x)
cout<< *x << “ “;
// declaring empty( ) function
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( ) 函数?
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 << " ";
// using size( ) function to print No. of element in list
cout<< " Size of List" << list.size( );
return 0;
}输出
如果我们运行以上代码,它将生成以下输出
Input – List: M A R C H Output – Size of List: 5
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP