Reputation: 1
I dont know if its even possible but i want to make this function that calculates mean of vector accept both float and double. is there any way to make it? thanks.
#include <numeric>
#include <stdint.h>
#include <vector>
int mean(std::vector<float> var)
{
int number = var.size();
int varAcc = std::accumulate(var.begin(), var.end(), 0);
return varAcc / number;
}```
Upvotes: 0
Views: 1209
Reputation: 1409
You can use templates to make it work with all the types.
template<typename T>
T mean(const std::vector<T>& var)
{
int number = var.size();
T varAcc = std::accumulate(var.begin(), var.end(), T{});
return varAcc / number;
}
This is how you write less code and make things work on the types that supports the operations used in the function templates and template classes.
Upvotes: 1