Reputation: 4969
I would like to write a generic function calculating sum of elements in a STL container. The way I go about it is as follows (t
is a container):
template <typename T> double Sum(const T& t){
typename T::reverse_iterator rit = t.rbegin();
double dSum = 0.;
while( rit != t.rend() ){
dSum += (*rit);
++rit;
}
return dSum;
}
but I'm getting a whole lot of errors. I guess the problem is about 2nd line where I define the iterator? Would appreciate any help :)
Upvotes: 0
Views: 581
Reputation: 27385
Would appreciate any help :)
If you are doing this in production code, use std::accumulate
instead: it is standard, production quality code and should be already implemented and tested.
If you are writing this as an exercise, consider the following:
Sum
).For example (with std::accumulate) you can call it as std::accumulate(t.begin(), t.end(), 0)
or std::accumulate(t.rbegin(), t.rend(), 0)
or std::accumulate(t.cbegin(), t.cend(), 0)
.
receive begin iterator by value and increment it directly (it will save you the need to declare rit internally; receive the end iterator by const reference.
optional: set a default value for the sum (the default should be zero).
Upvotes: 1
Reputation: 55897
Should be
typename T::const_reverse_iterator rit = t.rbegin();
since t
is const
and rbegin
for const
container returns const_reverse_iterator
, that cannot be converted to reverse_iterator
.
Will be better to use std::accumulate
, instead of your own function, like this
double result = std::accumulate(c.rbegin(), c.rend(), 0.0);
Upvotes: 5