English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ List front() usage and example

C++ List (List)

C ++ The List front() function returns the first element of the list. It provides a direct reference to the element.

The difference between front() and begin()

The begin() function returns an iterator to the element, while the front() function returns a direct reference to the same element.

Syntax

reference front();

Parameters

It does not contain any parameters.

Return value

It returns a direct reference to the first element.

Example1

Let's look at a simple example when the list contains integer values.

#include <iostream> #include <vector> using namespace std;
int main()
{
    std::listli={1,2,3,4,5};
    std::cout << "front() is:" << li.front() << std::endl;
    return 0;
}

Output:

front() is : 1

In this example, the front() function returns the first element of the list, that is1。

Example2

Let's see a simple example, the list contains character values.

#include <iostream> #include <vector> using namespace std;
int main()
{
    std::list li = {'j', 'a', 'v', 'a'};
    std::cout << "front() is:" << li.front() << std::endl;
    return 0;
}

Output:

front() is : j

In this example, the front() function returns the first character of the list, that is, j.

C++ List (List)