C++ STL 中的 forward_list::front() 和 forward_list::empty()
在本文中,我們將討論 C++ 中 forward_list::front() 和 forward_list::empty() 函式的工作原理、語法和示例。
什麼是 STL 中的 Forward_list?
Forward list 是序列容器,允許在序列中的任何位置進行常數時間的插入和刪除操作。Forward list 實現為單鏈表。順序由每個元素與其在序列中下一個元素的連結來保持。
什麼是 forward_list::front()?
forward_list::front() 是 C++ STL 中一個內建函式,宣告在 <forward_list> 標頭檔案中。front() 返回一個迭代器,該迭代器指向 forward_list 容器中的第一個元素。
語法
forwardlist_container.front();
此函式不接受任何引數。
返回值
此函式返回指向容器第一個元素的迭代器。
示例
/* 在下面的程式碼中,我們建立一個 forward list 並向其中插入元素,然後我們將呼叫 front() 函式來獲取 forward list 中的第一個元素。 */
#include <forward_list>
#include <iostream>
using namespace std;
int main(){
forward_list<int> forwardList = {2, 6, 1, 0 };
cout<<"my first element in a forward list is: ";
cout<<forwardList.front();
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
my first element in a forward list is: 2
什麼是 forward_list::empty()?
forward_list::empty() 是 C++ STL 中一個內建函式,宣告在 <forward_list> 標頭檔案中。如果 forward list 容器為空,empty() 返回 true,否則返回 false。此函式檢查容器的大小是否為 0。
語法
bool forwardlist_container.empty();
此函式不接受任何引數。
返回值
如果容器的大小為 0,此函式返回 true,否則返回 false。
示例
/* 在下面的程式碼中,我們建立一個 forward list,然後我們將透過呼叫 empty() 函式來檢查列表是否為空。之後,我們將向 forward list 插入元素,然後我們將再次呼叫 empty() 函式來檢查結果。 */
#include <forward_list>
#include <iostream>
using namespace std;
int main(){
forward_list<int> forwardList = {};
if (forwardList.empty()){
cout << "Yess forward list is empty\n";
}
forwardList = {1, 3, 4, 5};
if (forwardList.empty()){
cout << "Yess forward list is empty\n";
} else {
cout << "No forward list is not empty\n";
}
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
Yess forward list is empty No forward list is not empty
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP