C++ Online Compiler
Example: Largest Element using std::max_element in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Largest Element using std::max_element #include <iostream> #include <algorithm> // Required for std::max_element #include <vector> // Required if using std::vector, but not for raw array here int main() { // Step 1: Declare and initialize an array int arr[] = {12, 45, 9, 78, 23, 56}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate array size // Step 2: Use std::max_element to get an iterator to the largest element // It takes two iterators (or pointers for raw arrays): // beginning of the range and one past the end of the range. int* maxElementPtr = std::max_element(arr, arr + n); // Step 3: Dereference the iterator/pointer to get the actual value int maxElement = *maxElementPtr; // Step 4: Display the largest element std::cout << "The largest element in the array is: " << maxElement << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS