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