How to Access First Element of a List in C++?
In C++, a list is a sequential container that allows constant time insertions and deletions and allows the users to store data in non-contiguous memory locations. In this article, we will learn how to access the first element in the list in C++.
Examples:
Input: myList ={1, 2, 3, 4, 5} Output: The first element of the list is 1.
Access the First Element of a List in C++
To access the first element in a std::list in C++, we can use the std::list::front() method which provides a reference to the first element present in the list.
Syntax of std::list::front()
list_name.front();
C++ Program to Access the First Element of a List
The following program illustrates how we can access the first element of a list in C++.
// C++ Program to illustrate how we can access the first
// element of a list
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> l1 = { 1, 2, 3, 4, 5 };
// Access the first element using front()
int firstElement = l1.front();
// Print the first element
cout << "First Element of the list is: " << firstElement
<< endl;
return 0;
}
Output
First Element of the list is: 1
Time Complexity:O(1)
Auxiliary Space:O(1)
Contact Us