C++ vector::end() with example

In C++, the standard library provides us with vectors, which are dynamic arrays. It consists of multiple homogeneous objects, which can be accessed by their position in the vector. It is automatically resized (if needed) and thus, eliminates the need to explicitly use keywords like new and delete. The vector::end() is a C++ Standard Library function which returns an iterator to a theoretical element that follows the last element in the vector.

Syntax:

vector_name.end();

Parameter: The vector::end() function does not accept any parameter.
Return value: The vector::end() function returns an iterator to the element past the last element.

Example of vector::end() function

vector<int> VEC{8,7,6,5};
iterator it = VEC.end(); // it is an iterator after the element 5

Since the range of functions in the standard library does not include the closing iterator, vector::end() can be used to ensure that the last element is included.

#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> vec;
  vec.push_back(10);
  vec.push_back(9);
  vec.push_back(8);
  vec.push_back(7);
  cout<<"The elements are: \n";
  for (vector<int>::iterator it = vec.begin() ; it != vec.end(); ++it)
    cout<<*it<<"   ";
  return 0;
}

Output

The elements are:
10 9 8 7


This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top