C++ <list> front function

C++ container class <list>


frontis used in list toGet the first elementof the function.

frontIt is a member function of the container class, used to return the first element of the linked list.

The time complexity is O(1).

Word Definitions: frontIt means "front", i.e., get the first element.


Basic syntax and parameters

Syntax format

reference front();
const_reference front() const;

Function description

  • Return Value: Returns a reference to the first element.
  • Note: The linked list cannot be empty.

Example

Example 1: Get the first element

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {10, 20, 30, 40, 50};

    std::cout << First element: << numbers.front() << std::endl;

    // modify the first element
    numbers.front() = 100;
    std::cout << Modified first element: << numbers.front() << std::endl;

    return 0;
}

Expected output:

第一个元素: 10
修改后第一个元素: 100

C++ container class <list>

other extensions