P
P
Programmer20122015-12-29 14:17:45
C++ / C#
Programmer2012, 2015-12-29 14:17:45

template functions. What are the benefits?

Good day!
Please advise which of the two functions is better to use?
in C style:

double GetAverage(double arr[], int numElems) {
        double total = 0.0;
        for(int h = 0; h < numElems; ++h)
            total += arr[h] / numElems;
        return total;
    }

or template:
template <typename ForwardIterator>
    double GetAverage(ForwardIterator begin, ForwardIterator end) {
        return std::accumulate(begin, end, 0.0) / std::distance(begin, end);
    }

The example from the c++ manual says that it is preferable to use a template, but I'm confused by calling 2 additional functions in the template.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Moseychuk, 2015-12-29
@Programmer2012

but I'm confused by calling 2 additional functions in the template
  1. Functions will be inlined, so you don't have to worry about performance.
  2. You have slightly different algorithms. In the template, no one forbids you to loop through the iterators and calculate the average in the same way as in the first option.
  3. Using stl functions is preferable to your bike. The code is easier to read. I saw accumulateit and immediately thought of a bundle. And the first example had to get a grasp. In addition, it is also not optimal - after all, division can be taken out of the cycle.
  4. This template option is much more flexible - it can be used with any container that implements an iterator.

P
Peter, 2015-12-29
@petermzg

Если код функции должен работать с разными типами входных параметров, то имеет смысл использовать шаблоны.
Если только с одним типом, то нет.

M
maaGames, 2015-12-30
@maaGames

Реализации функций не эквивалентны и будут возвращать разный результат, практически со 100% вероятностью.
В первом случае суммируется частное от значения и количества элементов, а во втором элементы сперва суммируются, а потом делятся на число элементов. В первом случае больше накопление погрешностей вычислений, больше операций деления, следовательно, меньшая точность вычислений и меньшая скорость работы.
Если в первом варианте деление вынести из цикла, то различие будет только в гибкости кода.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question