C++ vector back() function
Example
Get the last element of a vector:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars.back();
Try it Yourself »
Definition and Usage
The back()
function returns a reference to the last element in a vector.
Tip: Values can be assigned to the reference, which will change the vector.
Syntax
vector.back();
Parameter Values
None.
Technical Details
Returns: | A reference to the last element in the vector. |
---|
More Examples
Example
Change the last element in a vector:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.back() = "Toyota";
for (string car : cars) {
cout << car << " ";
}
Try it Yourself »
Related Pages
Read more about vectors in our Vector Tutorial.