C++ Array::end() Function



The C++ std::array::end() function is used to return an iterator pointing to the element following the last element of the array. This iterator does not point to a valid element but points the end of the array, making it useful for traversing or iterating through the array using loops.

Syntax

Following is the syntax for std::array::end() function.

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

Parameters

It does not accepts any parameter.

Return Value

It returns an iterator pointing to the past-the-end element in the array.

Exceptions

This function never throws exception.

Time complexity

Constant i.e. O(1)

Example 1

In the following example, we are going to consider the basic usage of the end() function.

 #include <iostream> #include <array> using namespace std; int main(void) { array < int, 5 > arr = {10,20,30,40,50}; auto start = arr.begin(); auto end = arr.end(); while (start < end) { cout << * start << " "; ++start; } cout << endl; return 0; } 

Output

Output of the above code is as follows −

 10 20 30 40 50 

Example 2

Consider the following example, where we are going to apply end() function on the character array.

 #include <iostream> #include <array> using namespace std; int main() { array < char, 5 > MyArray {'P','R','A','S','U'}; array < char, 5 > ::iterator it; for (it = MyArray.begin(); it != MyArray.end(); ++it) cout << * it << " "; return 0; } 

Output

Following is the output of the above code −

 P R A S U 

Example 3

Let's look at the following example, where we are going to consider the string array and applying the end() function.

 #include <iostream> #include <array> using namespace std; int main() { array < string, 2 > MyArray {"Tutorials","point"}; array < string, 2 > ::iterator it; it = MyArray.end(); it--; cout << * it << " "; it--; cout << * it << " "; return 0; } 

Output

If we run the above code it will generate the following output −

 point Tutorials 
array.htm
Advertisements