C++ STL 中的 list empty() 函式
在本文中,我們將討論 C++ 中 list::empty() 函式的工作原理、語法和示例。
什麼是 STL 中的 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
//call empty() function to check if list is empty or not
if (myList.empty())
cout << "my list is empty\n";
else
cout << "my list isn’t empty\n";
//push_back() is used to insert element in a list
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 的數字相乘,為此 -
首先使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP