Open In App

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

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Find the sum of all deque elements using the std::accumulate() function.
  • Find the number of elements in the deque using the std::deque::size() function.
  • Divide the sum of deque elements by the size to get the average of all elements in the deque.
  • Store the average in double data type to deal with floating point precisions.

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++
// 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)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads