In C++, std::list::front() gives you a reference to the first element of a std::list. You can read it, or assign to it to change the first element.
Because a list has no l[0], front() and back() are the main ways to reach the ends. 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 front with empty brackets. The list must not be empty.
C++
int a = l.front(); // read the first element
l.front() = 99; // change the first element
Call
What it does
l.front()
Returns a reference to the first element. On a const list it returns a const reference.
front() gives the element itself. begin() gives an iterator to it. The two are linked: l.front() equals *l.begin().
Library declarations
C++
reference front();
const_reference front() const;
Parameters
Parameter
Description
None
front() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
reference
A reference to the first element. For a const list, a const_reference.
C++ Examples
Example 1 — front() Reads the First Element
Print the first element of a list, and show that it is the same as *l.begin().
The function takes the list by const reference, so no copy is made and the list cannot be changed.
For the empty list, empty() is true, so front() is never called. That avoids undefined behavior.
For {4, 5} the check fails, so front() runs safely and prints 4.
Frequently Asked Questions
A reference to the first element of the list. You can read it or assign a new value to it.
The behavior is undefined. The program may crash or show garbage. Always check empty() first.
front() returns the first element itself (a reference). begin() returns an iterator that points at the first element. On an empty list begin() is still safe to compare, but dereferencing it is not.
A list has no operator[] or at(). Move an iterator with std::next(l.begin(), i) and dereference it. This walks node by node, so it is slow for big i.
Yes. It takes constant time because the list always knows its first node.