In C++, std::list::back() gives you a reference to the last element of a std::list. You can read it, or assign to it to change the last element.
A list is doubly linked, so reaching the last element is as quick as reaching the first one. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call back with empty brackets. The list must not be empty.
C++
int z = l.back(); // read the last element
l.back() = 0; // change the last element
Call
What it does
l.back()
Returns a reference to the last element. On a const list it returns a const reference.
Do not use *l.end() to get the last element. end() points one place after the last element. Use *std::prev(l.end()) or just 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. For a const list, a const_reference.
C++ Examples
Example 1 — back() Reads the Last Element
Print the last element of a list, and compare it with *std::prev(l.end()).