samedi 3 juillet 2021

C++ sum function that works for doubles and size_t

I want to sum vectors of doubles or size_t values in C++.

I can use C++11 or higher, so I am using the function from here:

template <typename T> T sum(const std::vector<T> &vec)
{
  return std::accumulate(vec.begin(), vec.end(), 0.0);
}

This works for doubles, but for std::vector<size_t>, this returns the wrong result. The sum is way off – like 9100 instead of 600000.

Instead, when I do:

size_t sum_size_t(const std::vector<size_t> &vec) {
  return std::accumulate(vec.begin(), vec.end(), (size_t) 0);
}

This still returns the same wrong result.

And when I try to use the approach suggested to automatically deduce the type with:

template <typename T> T sum(const std::vector<T> &vec)
{
  return std::accumulate(vec.begin(), vec.end(), decltype(vec)::value_type(0));
}

I get this error:

error: type 'decltype(vec)' (aka 'const vector<unsigned long> &') cannot be used prior to '::' because it has no members

I don't quite understand this error message, and I am unsure how to apply the suggestions from another question.

This simple code works:

size_t total_sum = 0;
for (const auto &e : vec) {
  total_sum += e;
}

So how do I write a generic function that works for both doubles and size_t entries?

Aucun commentaire:

Enregistrer un commentaire