C++ 迭代器::end() 函式



C++ 中的 C++ iterator::end() 函式返回一個指向容器最後一個元素之後元素的指標。此元素包含前一個元素的地址,但它是虛擬元素,而不是實際元素。

迭代器是一個指向容器內元素的物件(類似於指標)。迭代器可用於迴圈遍歷容器的內容。我們可以使用它們訪問該特定位置處的材料,並且可以將它們視為類似於指向特定方向的指標。

語法

以下是 C++ iterator::end() 函式的語法:

auto end(Container& cont)
   -> decltype(cont.end());

auto end(const Container& cont)
   -> decltype(cont.end());

Ty *end(Ty (& array)[Size]);

引數

  • cont - 它指示返回 cont.end() 的容器。
  • array - 型別為 Ty 的物件陣列。

示例 1

讓我們考慮以下示例,我們將使用 end() 函式並檢索輸出。

#include<iostream>
#include<iterator>
#include<vector>
using namespace std;
int main() {
   vector<int> tutorial = {1,3,5,7,9};
   vector<int>::iterator itr;
   cout << "Result: ";
   for (itr = tutorial.begin(); itr < tutorial.end(); itr++) {
      cout << *itr << " ";
   }
   cout << "\n\n";
   return 0;
}

輸出

當我們編譯並執行上述程式時,將產生以下結果:

Result: 1 3 5 7 9

示例 2

檢視另一個場景,我們將使用 end() 函式並檢索輸出。

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main () {
   int array[] = {11,22,33,44,55};
   vector<int> tutorial;
   for(auto it = begin(array); it != end(array); ++it)
      tutorial.push_back(*it);
   cout<<"Elements are: ";
   for(auto it = begin(tutorial); it != end(tutorial); ++it)
      cout<<*it<<" ";
   return 0;
}

輸出

執行上述程式後,將產生以下結果:

Elements are: 11 22 33 44 55 
廣告