Skip to main content

std::vector front() method

// prism-push-types:reference,const_reference
// Non const version
constexpr reference front();

// Const version
constexpr const_reference front() const;

Returns a reference

to the first element in the container.

Undefined Behavior

Calling front() on an empty container is undefined behavior

.

Parameters

(none)

Return value

Reference to the first element.

Complexity

Constant - O(1).

Notes

For a container c, the expression c.front() is equivalent to *c.begin() and c[0].

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'o', 'm', 'g', 'w', 't', 'f'};

if (!letters.empty()) {
std::cout << "The first character is '" << letters.front() << "'.\n";
}
}
Output
The first character is 'o'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::vector front() method

// prism-push-types:reference,const_reference
// Non const version
constexpr reference front();

// Const version
constexpr const_reference front() const;

Returns a reference

to the first element in the container.

Undefined Behavior

Calling front() on an empty container is undefined behavior

.

Parameters

(none)

Return value

Reference to the first element.

Complexity

Constant - O(1).

Notes

For a container c, the expression c.front() is equivalent to *c.begin() and c[0].

Example

Main.cpp
#include <array>
#include <iostream>

int main()
{
std::vector<char> letters {'o', 'm', 'g', 'w', 't', 'f'};

if (!letters.empty()) {
std::cout << "The first character is '" << letters.front() << "'.\n";
}
}
Output
The first character is 'o'.
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.