Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vector::front — access the first element

`front()` accesses a vector’s first element in constant time. If the vector might be empty, check `empty()` before calling it.

Version: ISO C++23; implementation support may vary

Syntax

// Member declarations in std::vector<T, Allocator>, declared in <vector>
constexpr reference front();
constexpr const_reference front() const;

std::vector::front is a member function declared in <vector> that accesses the first element without removing it. For a nonempty vector v, v.front() is equivalent to *v.begin() and accesses the same element as v[0]. It takes O(1) time. Both overloads have been constexpr since C++20.

In C++23, calling front() on an empty vector is undefined behavior. Do not rely on an exception or diagnostic. If the vector might be empty, call front() only when !v.empty() is true. If you want missing-element access to throw instead, use v.at(0), which throws std::out_of_range when the vector is empty.

For std::vector<T> with T other than bool, the non-const overload returns T&, so assigning to v.front() changes the element. The const overload returns const T&, which does not let you modify the element through that reference. For std::vector<bool>, the non-const overload returns a proxy object by value that can modify the bit, whereas the const overload returns a bool value.

Keeping a reference does not extend the element’s lifetime. Do not use it after the element is erased, the vector is destroyed, or its storage is reallocated, for example when push_back() needs to grow the capacity. Do not keep a reference returned by front() on a temporary vector beyond the full expression that created that vector.

Examples

#include <iostream>
#include <vector>

void print_first(const std::vector<int>& values)
{
    if (values.empty()) {
        std::cout << "empty\n";
        return;
    }
    std::cout << values.front() << '\n';
}

int main()
{
    std::vector<int> values{7, 9};
    int& first = values.front();
    first = 42;

    print_first(values);
    print_first(std::vector<int>{});
}

Result

42
empty

Assigning through `first` changes the first element to `42`. `print_first` reads it through the const overload and prints `empty` for an empty vector without calling `front()`.

Related lessons

  • C++ · Lesson 28 · Advanced · Version: 3

Sources