![]() |
VOOZH | about |
In C++, the vector back() is a built-in function used to retrieve the last element of the vector. It provides a reference to the last element which allows us to read or modify it directly.
Let’s take a quick look at a simple example that illustrates the vector back() method:
20
This article covers the syntax, usage, and common examples about the vector back() method in C++ STL:
Table of Content
The vector back() is a member method of std::vector class defined inside <vector> header file.
v.back();
Parameters:
Return Value:
The below examples illustrate how to use vector back for different purposes and in different situation:
5 10 15 50
Vector is empty!
Explanation: Calling back() on an empty vector causes undefined behaviour. To prevent this, always check if the vector is not empty.
The vector back() and vector end() can both be used in to access the last element of the vector, but they have some differences:
| Feature | Vector back() | Vector end() |
|---|---|---|
| Purpose | Returns a reference to the last element of the vector. | Returns an iterator pointing to one past the last element. |
| Return Type | Reference (T&) or constant reference (const T&). | vector<T>::iterator type. |
| Usage | Only used for direct access to the last element. | Can be used for iteration and access. |
| Syntax | v.back(); | *(v.end() - 1); |
In Short,