C++ - Array back() Function
The C++ array::back function is used to return a reference to the last element of the array. Please note that, Unlike the array::rbegin function, which returns the reverse iterator pointing to the last element, it returns the a direct reference to the same element of the array.
Syntax
reference back(); const_reference back() const;
Parameters
No parameter is required.
Return Value
A reference to the last element of the array.
Time Complexity
Constant i.e, Θ(1).
Example:
In the below example, the array::back function is used to access the last element of the array MyArray.
#include <iostream> #include <array> using namespace std; int main (){ array<int, 5> MyArray{10, 20, 30, 40, 50}; cout<<"The last element of MyArray is: "; cout<<MyArray.back(); cout<<"\n\nAdd 100 to the last element of the MyArray.\n\n"; MyArray.back() = MyArray.back() + 100; cout<<"Now, The last element of MyArray is: "; cout<<MyArray.back(); return 0; }
The output of the above code will be:
The last element of MyArray is: 50 Add 100 to the last element of the MyArray. Now, The last element of MyArray is: 150
❮ C++ - Array