How to Find the Maximum Element in a List in C++?
In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows us to store data in non-contiguous memory locations efficiently. In this article, we will learn how to find the maximum element in a list in C++.
Example:
Input: myList = {30, 20, 10, 50, 40}; Output: The maximum element in the list is: 50
Finding the Maximum Element in a List in C++
To find the maximum element in a std::list, we can use the std::max_element() algorithm that returns an iterator pointing to the maximum value present in the list.
Syntax to Find the Maximum Element in a List
*max_element(begin, end);
Here, begin and end are iterators denoting the range of elements in the list.
C++ Program to Find the Maximum Element in a List
The below program demonstrates how we can use the std::max_element function to find the maximum element in a list in C++.
// C++ program to demonstrates how we can use the
// std::max_element function to find the maximum element in
// a list
#include <algorithm>
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> myList = { 30, 20, 10, 50, 40 };
// Finding the maximum element
int maxi = *max_element(myList.begin(), myList.end());
// Printing the maximum element of the list
cout << "The maximum element in the list is : " << maxi
<< endl;
return 0;
}
Output
The maximum element in the list is : 50
Time Complexity: O(N), where N denotes the number of elements in the list
Auxiliary Space: O(1)