In C++, std::vector::front() returns the first element of a std::vector. It is the same as d[0], but it reads better.
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 front with empty brackets. It takes no arguments.
C++
v.front();
v.front() = 1;
Call
What it does
v.front()
Reads the first element.
v.front() = 1
Replaces the first element with a new value.
The last element has a matching function: back(). A vector has no pop_front(); erase at begin() if you must remove the first element.
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, which is the same as d[0] and *d.begin().
The helper takes the vector by const reference so it can only read.
For the empty vector, empty() is true, so front() is never called.
For {7, 8} the check fails and front() safely prints 7.
Frequently Asked Questions
It returns a reference to the first element of the vector. That is the element at index 0.
No. Calling front() on an empty vector is undefined behavior. Check empty() first.
front() returns the first element itself. begin() returns an iterator that points to it. *v.begin() gives the same value as v.front().
No. front() only looks at it. To remove the last element use pop_back(). To remove the first element use erase(v.begin()), which is slower on a vector.
Both read the first element when the vector is not empty. at(0) throws if the vector is empty; front() is undefined behavior on an empty vector.