C++ iterator::end() Function



The C++ iterator::end() function in C++, returns a pointer pointing to the element that follows the container's final element. This element includes the address of the previous element but is a virtual element rather than a real one.

An iterator is an object (similar to a pointer) that points to an element inside the container. Iterators can be used to cycle through the contents of the container. We may access the material at that specific spot utilizing them, and they can be seen as something similar to a pointer pointing in a certain direction.

Syntax

Following is the syntax for C++ iterator::end() Function −

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

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

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

Parameters

  • cont − it indicates the container that returns cont.end().
  • array − an array of objects of type Ty.

Example 1

Let's consider the following example, where we are going to use the end() function and retrive the output.

#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;
}

Output

When we compile and run the above program, this will produce the following result −

Result: 1 3 5 7 9

Example 2

Look into the another scenario, where we are going to use end() function and retrieving the output.

#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;
}

Output

On running the above program, it will produce the following result −

Elements are: 11 22 33 44 55 
Advertisements