C++ STL 中的 list end() 函式


在本文中,我們將討論 C++ 中 list::end() 函式的工作原理、語法和示例。

什麼是 STL 中的 List?

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

什麼是 list::end()?

list::end() 是 C++ STL 中一個內建函式,宣告在 <list> 標頭檔案中。end() 返回一個迭代器,該迭代器指向列表容器中末尾位置的下一個元素。此函式不指向容器中的任何元素。

此函式通常與 list::begin() 一起使用,以給出特定列表容器的範圍。

語法

list_container.end();

此函式不接受任何引數。

返回值

此函式返回指向列表容器末尾元素之後的迭代器。

示例

/* 下面的程式碼使用 end() 函式遍歷列表中存在的元素。 */

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //insert elements to List suing push_back() function
   myList.push_back(67);
   myList.push_back(12);
   myList.push_back(32);
   myList.push_back(780);
   myList.push_back(78);
   cout<<"elements in the list are :\n";
   for (auto j = myList.begin(); j!= myList.end(); j++){
      cout << *j << " ";
   }
   return 0;
}

示例

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

Elements in the list are:
67 12 32 780 78

示例

/* 下面的程式碼使用標頭檔案來訪問使用 end() 函式存在的列表中的元素。 */

 線上演示

#include <iostream>
#include <list>
int main (){
   //creating array of elements
   int values[] = {67, 12, 32, 780, 78};
   //inserting values to the list
   std::list<int> myList (values,values+5);
   std::cout << "elements in the list are :\n";
   //accessing list elements using iterator returned by an end() function
   for (std::list<int>::iterator i = myList.begin() ; i != myList.end(); ++i)
      std::cout << ' ' << *i;
   return 0;
}

輸出

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

Elements in the list are:
67 12 32 780 78

更新於:2020年3月2日

728 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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