C++ std::array::end
The std::array::end
function returns an iterator pointing to one past the last element of the array. This is commonly used in combination with begin()
to traverse the elements of the array or perform operations within a range.
Syntax of std::array::end
iterator end() noexcept;
const_iterator end() const noexcept;
Parameters
The std::array::end
function does not take any parameters.
Return Value
Returns an iterator (or a constant iterator for const
arrays) pointing to one past the last element of the array. This iterator can be used as an endpoint in range-based algorithms or loops.
Examples for std::array::end
Example 1: Traversing an Array Using std::array::end
This example demonstrates iterating through the elements of a std::array
using begin()
and end()
:
#include <iostream>
#include <array>
int main() {
std::array<int, 5> arr = {10, 20, 30, 40, 50};
std::cout << "Array elements: ";
for (auto it = arr.begin(); it != arr.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define an array: A
std::array
of size 5 is defined and initialized with the elements{10, 20, 30, 40, 50}
. - Use
begin()
andend()
: Thebegin()
function provides an iterator pointing to the first element, andend()
provides an iterator pointing to one past the last element. - Iterate through the array: A for loop is used to traverse the array, and each element is accessed using the dereference operator
*it
.
Output:
Array elements: 10 20 30 40 50
Example 2: Using std::array::end with Standard Algorithms
This example demonstrates using std::array::end
with the std::reverse
algorithm:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
std::cout << "Original array: ";
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
std::reverse(arr.begin(), arr.end());
std::cout << "Reversed array: ";
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Original array: The array
arr
is initialized with elements{1, 2, 3, 4, 5}
. - Use
std::reverse
: Thestd::reverse
algorithm reverses the range of elements betweenarr.begin()
andarr.end()
. - Print reversed array: A range-based for loop is used to print the reversed array.
Output:
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
Exception Handling in std::array::end
The std::array::end
function does not throw exceptions as it is marked noexcept
. It guarantees safe operation for accessing the end iterator of the array.