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?
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.