Templated iterator functions

I've been trying to make a range-based function for a statistics library, but I'm having trouble making it a true template function.

This works (if I insert std::vector<int>::iterator as the arguments)
1
2
3
4
5
6
7
8
9
10
int sum(std::vector<int>::iterator first, std::vector<int>::iterator last)
{
    int sum = 0;
    while (first != last)
    {
        sum += *first;
        ++first;
    }
    return sum;
}


This works for pre-C++0x arrays:
1
2
3
4
5
6
7
8
9
10
11
template <typename T>
T sum(T* first, T* last)
{
    T sum = T(0);
    while(first != last)
    {
        sum += *first;
        ++first;
    }
    return sum;
}


However, I want something that will work with any STL (or custom) container with iterators and any array (pointer). Does anyone have any ideas?
Time to learn about std::iterator_traits

1
2
3
4
5
6
7
8
9
10
11
12
template<typename Iter>
int sum(Iter first, Iter last)
{
    typedef typename std::iterator_traits<Iter>::value_type val_t;
    val_t sum = val_t();
    while (first != last)
    {
        sum += *first;
        ++first;
    }
    return sum;
}

but in this particular case, you could have just called std::accumulate
Last edited on
Use std::accumulate algorithm declared in <numeric>.

All is done already before you!:)
Thanks guys! sum() was the most basic function that I'm doing. I wanted to do mean, median, mode, standard deviation, min, max, variance, correlations, entropy and skewness.

I checked out the possible implementation of std::accumulate from here:
http://cplusplus.com/reference/numeric/accumulate/
And it makes sense! What I was missing was template type for the init value. Of course, I'd rather not make people specify initial values just for the type, so std::iterator_traits looks nifty.

I wanted to do mean, median, mode, standard deviation, min, max, variance, correlations, entropy and skewness.

There's a library for that: http://www.boost.org/doc/libs/release/doc/html/accumulators.html
Topic archived. No new replies allowed.