max element in array c++ stl
To find the maximum element in an array using the C++ STL (Standard Template Library), you can follow these steps:
- Include the necessary header files:
#include <iostream>
#include <algorithm>
The <iostream>
header file is required for input/output operations, and the <algorithm>
header file is needed for using the std::max_element
function.
- Define the array:
int arr[] = {4, 7, 2, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
Here, we define an array arr
with some elements and calculate its size using the sizeof
operator.
- Use the
std::max_element
function:
auto max = std::max_element(arr, arr + size);
The std::max_element
function returns an iterator pointing to the maximum element in the range defined by arr
and arr + size
. The auto
keyword is used to automatically deduce the type of the iterator.
- Print the maximum element:
std::cout << "The maximum element is: " << *max << std::endl;
The *max
dereferences the iterator to get the actual value of the maximum element, which is then printed using std::cout
.
Here's the complete code:
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {4, 7, 2, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
auto max = std::max_element(arr, arr + size);
std::cout << "The maximum element is: " << *max << std::endl;
return 0;
}
This code will output:
The maximum element is: 9
The std::max_element
function from the C++ STL provides an efficient way to find the maximum element in an array without having to write a loop yourself. It takes advantage of the underlying implementation to find the maximum element in logarithmic time complexity.