In C++, std::vector::back() returns the last element of a std::vector. You do not need to calculate size() - 1 yourself.
It returns a reference, so you can read the value or change it. The vector must have at least one element. Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call back with empty brackets. It takes no arguments.
C++
v.back();
v.back() = 99;
Call
What it does
v.back()
Reads the last element.
v.back() = 99
Replaces the last element with a new value.
The first element has a matching function: front(). To remove the last element, use pop_back().
Library declarations
C++
reference back();
const_reference back() const;
Parameters
Parameter
Description
None
back() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Reference
A reference to the last element, which is the same as d[d.size() - 1].