Open In App

How to Find Average of All Elements in a Deque in C++?

In C++, a deque (double-ended queue) is a container class template that allows fast insertion and deletion at both its beginning and end. In this article, we will learn how to find the average (or mean) of all elements in a deque in C++.

Example:

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

Output: 
mean = 3

Find the Average of All Elements in a Deque in C++

To find the average or mean of all elements in a deque in C++, we can use the std::accumulate() function to calculate the sum and then divide it by the number of elements that can be found using std::deque::size().

Approach

C++ Program to Find the Average of All Elements in a Deque

The below program demonstrates how we can find the average of all elements in a deque in C++.

// C++ Program to demonstrate how we can find the average of
// all elements in a deque
#include <deque>
#include <iostream>
#include <numeric>
using namespace std;

int main()
{
    // Initializing a deque with some elements
    deque<int> dq = { 1, 2, 3, 4, 5 };

    // Calculating the sum of elements using std::accumulate
    int sum = accumulate(dq.begin(), dq.end(), 0);

    // Calculating the number of elements in the deque
    int size = dq.size();

    // Calculating the average
    double average = static_cast<double>(sum) / size;

    // Printing the average of deque elements
    cout << "Average of Deque Elements: " << average
         << endl;

    return 0;
}

Output
Average of Deque Elements: 3

Time Complexity: O(N), here N is the number of elements in the deque.
Auxiliary Space: O(1)



Article Tags :