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 
广告

© . All rights reserved.