Find Maximum Element of an Array Using STL in C++



In C++, one common task is to find the largest number in an array. An array is just a collection of values, and sometimes we need to find the highest value in that collection. For example, consider the array:

int arr[] = {11, 13, 21, 45, 8};

In this case, the largest element is 45. Similarly, for the array:

int arr[] = {1, 9, 2, 5, 7};

The largest number is 9.

In this article, we will show you how to find the largest number in an array using different methods in C++, including some built-in features from the Standard Template Library (STL).

C++ Programs to Find Maximum Element in an Array

There are multiple ways to find the maximum element in an array in C++. We will cover the following approaches:

Using std::max_element() from STL

In this approach, we use the std::max_element() function, which is part of the C++ Standard Library. This function returns an iterator pointing to the maximum element in the array.

Example

In this example, we will use std::max_element() to find the maximum element in an array. The function takes two iterators, one for the start and one for the end of the array, and returns an iterator to the maximum element.

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};

    // Display the array
    std::cout << "The array is: ";
    for (const auto& num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Using std::max_element to find the maximum element
    auto maxElement = std::max_element(arr.begin(), arr.end());

    // Output the maximum element
    std::cout << "The maximum element is: " << *maxElement << std::endl;
    return 0;
}

Output

The output shows the maximum element of the array, which is 9.

The array is: 4 9 2 6 3 
The maximum element is: 9

Time Complexity: O(n), the function iterates through the array to find the maximum.

Space Complexity O(1), only a constant amount of space is used.

Using std::minmax_element() from STL

In this approach, we use the std::minmax_element() function, which returns a pair of iterators: the first pointing to the minimum element and the second pointing to the maximum element. We can use the second iterator to find the maximum element.

Example

In this example, we use std::minmax_element to find both the minimum and maximum elements in the array, but only the maximum element is displayed.

#include <iostream>
#include <algorithm> // For std::minmax_element
#include <vector>

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};

    // Display the original array
    std::cout << "Array: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Using std::minmax_element to find both min and max
    auto result = std::minmax_element(arr.begin(), arr.end());

    // Output the maximum element
    std::cout << "The maximum element is: " << *result.second << std::endl;
    return 0;
}

Output

Below is the output of the code, which displays the maximum element of the array.

Array: 4 9 2 6 3
The maximum element is: 9

Time Complexity: O(n), we scan the array once to find both the minimum and maximum elements.

Space Complexity: O(1), the space used is constant, as no extra data structures are needed.

Using std::sort() from STL

Another way to find the maximum element is by sorting the array in descending order. After sorting, the first element will be the maximum. This is an efficient method if sorting is already part of your algorithm.

Example

In this example, we use std::sort() to sort the array in descending order with std::greater<int>(), and then we access the first element, which is the maximum element.

#include <iostream>
#include <algorithm> // For std::sort and std::greater
#include <vector>

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};

    // Display the original array
    std::cout << "Array: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Sort the array in descending order
    std::sort(arr.begin(), arr.end(), std::greater<int>());

    // Output the maximum element (first element after sorting)
    std::cout << "The maximum element is: " << arr[0] << std::endl;
    return 0;
}

Output

Below is the output of the code, which displays the maximum element of the array.

Array: 4 9 2 6 3
The maximum element is: 9

Time Complexity: O(n log n), sorting the array takes O(n log n).

Space Complexity: O(1), sorting is done in-place, so the space complexity is constant.

Using a Simple Loop

In this approach, we manually iterate through the array, comparing each element to find the maximum value. It's simple and gives us complete control over the logic.

Example

In this example, we start by assuming that the first element is the maximum. Then, we iterate through the array and update the maxElement whenever we find a larger value. Finally, we print the largest value found, which is 9.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};

    // Display the original array
    std::cout << "Array: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Initialize the first element as the maximum
    int maxElement = arr[0];

    // Loop through the array to find the maximum element
    for (int i = 1; i < arr.size(); ++i) {
        if (arr[i] > maxElement) {
            maxElement = arr[i];
        }
    }

    // Output the maximum element
    std::cout << "The maximum element is: " << maxElement << std::endl;
    return 0;
}

Output

The output shows the array and the maximum element, which is 9.

Array: 4 9 2 6 3
The maximum element is: 9

Time Complexity: O(n), we loop through all elements once.

Space Complexity: O(1), only a constant amount of space is used.

Using a Recursive Function

This approach uses recursion to find the maximum element. We define a recursive function that compares the first element with the maximum of the rest of the array.

Example

In this example, we define a recursive function that compares the current element with the maximum of the remaining array. The function then calls itself on a smaller part of the array, returning the larger value.

#include <iostream>
#include <vector>

int findMax(const std::vector<int>& arr, int index) {
    // Base case: if we've reached the last element
    if (index == arr.size() - 1) {
        return arr[index];
    }
    // Recursive call to find the maximum of the rest
    int maxRest = findMax(arr, index + 1);
    
    // Return the maximum of the current element and the rest
    return (arr[index] > maxRest) ? arr[index] : maxRest;
}

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};
    
    // Display the original array
    std::cout << "Array: ";
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Start recursion from the first element
    int maxElement = findMax(arr, 0);

    // Output the maximum element
    std::cout << "The maximum element is: " << maxElement << std::endl;
    return 0;
}

Output

Below is the output of the code, which displays the maximum element of the array.

Array: 4 9 2 6 3
The maximum element is: 9

Time Complexity: O(n), we recursively check each element.

Space Complexity: O(n), recursion requires additional stack space.

Using Priority Queue

In this approach, we use a priority queue(heap) to find the maximum element. By default, a priority queue in C++ is a max-heap, so the largest element is always at the top.

Example

#include <iostream>
#include <algorithm> // For std::max_element
#include <vector>

int main() {
    std::vector<int> arr = {4, 9, 2, 6, 3};

    // Display the array
    std::cout << "The array is: ";
    for (const auto& num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Using std::max_element to find the maximum element
    auto maxElement = std::max_element(arr.begin(), arr.end());

    // Output the maximum element
    std::cout << "The maximum element is: " << *maxElement << std::endl;
    return 0;
}

Output

Below is the output of the code, which displays the maximum element of the array.

The array is: 4 9 2 6 3 
The maximum element is: 9

Time Complexity: O(n log n), inserting each element into the priority queue takes O(log n).

Space Complexity: O(n), we store all elements in the priority queue.

Conclusion

In this article, we looked at different ways to find the maximum element in an array using C++. Methods like std::max_element(), std::minmax_element(), and sorting are simple and effective. Depending on the situation, each method offers a good solution with different levels of difficulty.

Updated on: 2025-02-14T18:04:33+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements