YetiCodeCamp - C++ for Beginners

Companion website for the C++ for Beginners YouTube video series.

C++ Vector back() Function


The C++ vector.back() function returns a reference to the last element of a vector. This function does not take any parameters.

Syntax:

Example, using a vector “v1”.

v1.back();

Returns the value in the last element of the vector.





This example is a complete program using the vector back() function to return the value of the last element in a vector.

#include<iostream>
#include<vector>

int main()
{
std::vector<std::string> month{"Jan","Feb","Mar","Apr","May","Jun",
                               "Jul","Aug","Sep","Oct","Nov","Dec"};
std::cout<<month.back();

return 0;
}  

Output: Dec