Open In App

How to Find the Maximum Element in a Deque in C++?

Last Updated : 22 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

in C++, double-ended queues, also known as deques, are sequence containers with the feature of insertion and deletion on both ends. They are similar to vectors but are more efficient for the insertion and deletion of elements from both ends. In this article, we will learn how to find the maximum element in a deque in C++.

Example

Input:
myDeque = {1,5,3,9,2}

Output:
Max Element in the Deque is: 9

Find the Biggest Element in a Deque in C++

To find the maximum element in a deque in C++, we can use the std::max_element method provided by the STL library of C++. This function returns the biggest element in the given range.

Syntax of std::max_element()

max_element(first, last);

where,

  • first: Iterator pointing to the beginning of the deque.
  • last: Iterator pointing to one position past the end of the deque.

C++ Program to Find the Maximum Element in a Deque

The following program illustrates how we can find the biggest number in a deque in C++:

C++
// C++ Program to illustrate how to find the maximum element
// in a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initialize a deque
    deque<int> dq = { 1, 5, 3, 9, 2 };

    // Using max_element function to get the iterator to max
    // element
    auto maxEle = max_element(dq.begin(), dq.end());

    // Print the elements of the deque
    cout << "Deque Elements: ";
    for (int x : dq) {
        cout << x << " ";
    }
    // Print the maximum Element by dereferencing the
    // iterator
    cout << "\nMax Element in the Deque is: " << *maxEle;

    return 0;
}

Output
Deque Elements: 1 5 3 9 2 
Max Element in the Deque is: 9

Time Complexity: O(N) where N denotes the size of the deque.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads