C++ Array::cend() Function
The C++ std::array::cend() function is used to return a constant iterator pointing to the element following the last element of the array. This function is used when you need a read only iterator that cannot modify the elements it points to.
Syntax
Following is the syntax for std::array::cend() function.
const_iterator cend() const noexcept;
Parameters
It does not accepts any parameter.
Return Value
This function returns a constant iterator pointing to the past-end element of the array.
Exceptions
This function never throws exception.
Time complexity
Constant i.e. O(1)
Example 1
Let's look at the following example, where we are going to use the cend() function on the integers array.
#include <iostream>
#include <array>
using namespace std;
int main() {
array < int, 8 > MyArray {1,2,3,4,5,6,7,8};
array < int, 8 > ::const_iterator cit;
for (cit = MyArray.cbegin(); cit != MyArray.cend(); ++cit)
cout << * cit << " ";
return 0;
}
Output
Output of the above code is as follows −
1 2 3 4 5 6 7 8
Example 2
Consider the following example, where we are going to modify the value and observing the output.
#include <iostream>
#include <array>
using namespace std;
int main(void) {
array < int, 5 > arr = {10,20,30,40,50};
auto it = arr.cend();
* it = 5;
return 0;
}
Output
Following is the output of the above code −
main.cpp: In function 'int main()':
main.cpp:8:8: error: assignment of read-only location '* it'
8 | *it = 5;
| ~~~~^~~
array.htm