0

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;
}```
raw_rice
  • 1
  • 1
  • in some sense the answer is already in your code. Look at `std::accumulate`, it is a template and it takes iterators as parameters, thats what enables it to accumulate elements of any type – 463035818_is_not_an_ai Feb 01 '21 at 10:28
  • You probably want to replace `int` by `float`/`double` and 0 by `0.`/`0.f`/`T{}`. – Jarod42 Feb 01 '21 at 10:32
  • 2
    if you want a function for 2 different types, then there are many more or less complicated solutions, the simple one is always to provide two overloads – 463035818_is_not_an_ai Feb 01 '21 at 10:36
  • `how can you make a function that accepts both float and double in c++` Like this: `void foo(float, double);` – eerorika Feb 01 '21 at 10:38
  • Is your problem, that you already don't get the expected result for your actual function, because `varAcc` and the return value is `int` and the result I truncated due to that. Or is that truncation on purpose, and you want to extend that function to also accept a `std::vector` besides the `std::vector`? – t.niese Feb 01 '21 at 10:45
  • @t.niese actually truncation already happens in `accumulate` due to the `0` initial value – 463035818_is_not_an_ai Feb 01 '21 at 10:47

1 Answers1

1

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.

foragerDev
  • 1,307
  • 1
  • 9
  • 22