Find average of all values present in a vector in C++
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <vector> #include <numeric> template<typename T> double getAverage(std::vector<T> const& v) { if (v.empty()) { return 0; } return std::accumulate(v.begin(), v.end(), 0.0) / v.size(); } int main() { std::vector<int> v = {5, 3, 8, 7, 9}; double avg = getAverage(v); std::cout << "Average is " << avg << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <numeric> template<typename T> double getAverage(std::vector<T> const& v) { if (v.empty()) { return 0; } return std::reduce(v.begin(), v.end(), 0.0) / v.size(); } int main() { std::vector<int> v = {5, 3, 8, 7, 9}; double avg = getAverage(v); std::cout << "Average is " << avg << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <vector> #include <numeric> template<typename T> double getAverage(std::vector<T> const& v) { if (v.empty()) { return 0; } double sum = 0.0; for (const T &i: v) { sum += (double)i; } return sum / v.size(); } int main() { std::vector<int> v = {5, 3, 8, 7, 9}; double avg = getAverage(v); std::cout << "Average is " << avg << std::endl; return 0; } |
Output:
Average is 6.4
That’s all about finding the average of all values present in a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)