C++ STL 中 forward_list max_size() 函式及示例
本任務演示 C++ STL 中 forward_list max_size() 函式的工作原理。
什麼是前向列表?
前向列表可以理解為單向連結串列,只能向前遍歷,不能向後遍歷,而列表則可以雙向遍歷,即元素包含兩個連結,一個指向前一個元素,另一個指向後一個元素。因此,前向列表速度較快,因為它們只需要儲存一個指向前一個元素的連結。可以在常數時間內插入和刪除前向列表中的元素。
什麼是 forward_list max_size() 函式?
forward_list::reverse( ) 是 C++ 標準模板庫 (STL) 中的一個函式,用於反轉前向列表中元素的順序。
語法
forwardlist_name.reverse( )
引數
此函式沒有任何引數。
返回值
此函式沒有任何返回值。它只執行反轉列表的操作。
例如
Input-: List of elements are: 57 99 54 34 84 Output–: Reversed elements of list are: 84 34 54 99 57 Input-: List of elements are: 40 30 60 90 70 Output–: Reversed elements of list are: 70 90 60 30 40
下面程式中使用的步驟如下
首先初始化列表
然後,我們在應用 reverse() 函式之前列印前向列表。
然後,我們定義了 C++ 標頭檔案中存在的 forward.reverse() 函式。
然後,我們將顯示反轉後的前向列表
示例
/* 在下面的程式碼中,我們建立了一個前向列表並將元素插入到列表中。現在,任務是使用 max_size() 函式檢查插入元素後前向列表的大小 */
#include <bits/stdc++.h>
using namespace std;
int main() {
//creating forward list
forward_list<int> myForwardList;
//add values to forward list
myForwardList.assign(3, 2);
cout << "The elements in my forward list are : ";
for (auto i=myForwardList.begin(); i!=myForwardList.end();i++)
cout << *i << " ";
cout << "\nThe size of my Forward List is: " << myForwardList.max_size();
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出
The elements in my forward list are : 2 2 2 The size of my Forward List is: 1152921504606846975
示例
/* 在下面的程式碼中,我們建立了一個前向列表。現在,任務是使用 max_size() 函式檢查前向列表的大小。 */
#include <bits/stdc++.h>
using namespace std;
int main() {
// creating forward list
forward_list<int> myForwardList;
cout << "\nsize of my forward list is: "<<myForwardList.max_size();
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出
size of my forward list is: 1152921504606846975
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP