C++ Standard Library C++ STL Library

C++ <iterator> - end() Function



The C++ <iterator> end() function returns an iterator pointing to the past-the-last element in the sequence.

  • Container: If the container's object is constant qualified, the function returns a const_iterator, else returns an iterator.
  • Array: The function returns a pointer to the end of the array.

The past-the-last element of a sequence 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

These function templates are defined in multiple headers which are: <iterator>, <array>, <deque>, <forward_list>, <list>, <map>, <regex>, <set>, <string>, <string_view>, <unordered_map>, <unordered_set> and <vector>.

Along with this, this function is overloaded with a different definition in headers <initializer_list> and <valarray>.

Syntax

//container version
template <class Container>
  auto end (Container& cont) 
    -> decltype (cont.end());
template <class Container>
  auto end (const Container& cont) 
    -> decltype (cont.end());

//array version
template <class T, size_t N>
  T* end (T(&arr)[N]);
//container version
template <class Container>
  auto end (Container& cont) 
    -> decltype (cont.end());
template <class Container>
  auto end (const Container& cont) 
    -> decltype (cont.end());

//array version
template <class T, size_t N>
  constexpr T* end (T(&arr)[N]) noexcept;
//container version
template <class Container>
  constexpr auto end (Container& cont) 
    -> decltype (cont.end());
template <class Container>
  constexpr auto end (const Container& cont) 
    -> decltype (cont.end());

//array version
template <class T, size_t N>
  constexpr T* end (T(&arr)[N]) noexcept;

Parameters

cont Specify a container or view with a end member function.
arr Specify an array.

Return Value

Returns an iterator to the past-the-last element of the sequence:

  • Container: If the container's object is constant qualified, the function returns a const_iterator, else returns an iterator.
  • Array: The function returns a pointer to the end of the array.

Example:

In the example below, the end() function is used to iterate over an array to insert all elements of the array into a vector.

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
 
int main (){
  int arr[] = {10, 20, 30, 40, 50};
  vector<int> vec;

  //iterate over array to insert all elements
  //of the array into an empty vector
  for(auto it = begin(arr); it != end(arr); ++it)
    vec.push_back(*it);

  //print the content of the vector
  cout<<"vec contains: ";
  for(auto it = begin(vec); it != end(vec); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

vec contains: 10 20 30 40 50

❮ C++ <iterator> Library