C++ Standard Library C++ STL Library

C++ <vector> - end() Function



The C++ vector::end function returns the iterator pointing to the past-the-last element of the vector container. The past-the-last element of the vector is the theoretical element that follows the last element. It does not point to any element, and hence could not be dereferenced.

C++ begin end

Syntax

iterator end();
const_iterator end() const;
iterator end() noexcept;
const_iterator end() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the past-the-last element of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::end function returns the iterator pointing to the past-the-last element of the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<string> MyVector{"Alpha","Coding","Skills"};
  vector<string>::iterator it;

  it = MyVector.end();
  it--;
  cout<<*it<<" ";
  it--;
  cout<<*it<<" ";
  it--;
  cout<<*it<<" ";
  return 0;
}

The output of the above code will be:

Skills Coding Alpha

Example:

Lets see another example where the vector called MyVector contains integer values and vector::end function is used with vector::begin function to specify a range including all elements of the vector container.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

10 20 30 40 50 

❮ C++ <vector> Library