C++ STL 中的 forward_list::reverse( )


本任務演示 C++ STL 中 forward_list::reverse( ) 函式的工作原理。

什麼是前向列表?

前向列表可以理解為單鏈表,只能向前遍歷,而不能向後遍歷;而在列表中,我們可以雙向遍歷元素,即元素包含兩個連結,一個用於指向下一個元素,另一個用於指向前一個元素。因此,前向列表速度很快,因為它只需要儲存一個指向下一個元素的連結。可以在常數時間內插入和刪除前向列表的元素。

什麼是 forward_list::reverse( ) 函式?

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() 函式。

  • 然後,我們將顯示反轉後的前向列表。

示例

// C++ code to demonstrate the working of forward_list::reverse( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
Int main( ){
   // initializing forward list
   forward_list<int> forward = {10,20,30,40,50};
   cout<< “ List of elements : ”;
   for(auto it = forward.start( ); it != forward.end( ); ++it)
      cout<< *it<< “ “;
   // defining of function that performs the reverse operation
   forward.reverse( );
   cout<< “ Reversed elements list”;
   for( auto it =forward.start( ); it != forward.end( ); ++it)
      cout<< *it<< “ “;
   return 0;
}

輸出

如果執行以上程式碼,則會生成以下輸出。

Reversed elements list : 50 40 30 20 10

更新於:2020年2月28日

216 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.