This post will discuss how to find the average of all values present in a vector in C++.

1. Using std::accumulate

A simple solution to add the elements of an STL container is using the std::accumulate function, which is defined in the header <numeric>. To get the average of all values in the vector, divide the total sum by the vector’s size. For example,

Download  Run Code

Output:

Average is 6.4

2. Using std::reduce

Starting with C++17, std::reduce should be preferred over std::accumulate. It is defined in header <numeric> and reduces the specified range using the default std::plus function object.

Download  Run Code

Output:

Average is 6.4

3. Using Loop

We can even write a custom procedure to calculate the average of all values present in a vector in C++. This can be implemented as follows, using a for-loop.

Download  Run Code

Output:

Average is 6.4

That’s all about finding the average of all values present in a vector in C++.