C++ STL 中的 list begin() 和 list end()


本任務演示 C++ STL 中 list begin() 和 list end() 函式的功能。

什麼是 STL 中的 List?

List 是一種資料結構,允許在序列中的任何位置進行常數時間的插入和刪除操作。List 以雙向連結串列的形式實現。List 允許非連續的記憶體分配。與陣列、向量和雙端佇列相比,List 在容器中任何位置進行元素的插入、提取和移動操作的效能更好。在 List 中,直接訪問元素的速度較慢,並且 List 與 forward_list 類似,但 forward_list 物件是單向連結串列,只能向前迭代。

什麼是 begin()?

list begin() 用於返回指向列表第一個元素的迭代器。

語法

list_name.begin( )


什麼是 end()?

list end() 用於返回指向列表最後一個元素的迭代器。

語法

list_name.end( )

示例

輸出 - 列表 - 10 11 12 13 14

輸出 - 列表 - 66 67 68 69 70

可以遵循的方法

  • 首先,我們初始化列表

  • 然後,我們定義 begin() 和 end()。

使用上述方法,我們可以使用 begin() 和 end() 函式列印列表。

示例

/ / C++ code to demonstrate the working of begin( ) and end( ) function in STL
#include <iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
   / / print the list
   cout<< “ Elements in List: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<> *x << “ “;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出

Elements of List: 11 12 13 14 15 16 17 18 19 20

示例

/ / C++ code to demonstrate the working of list begin( ) and end( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List list = { ‘D’, ‘E’, ‘S’, ‘I’, ‘G’, ‘N’ };
   / / print the list
   cout << “ Elements in List: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << “ “;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出

Elements in List: D E S I G N

更新於:2020年2月26日

493 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告