Simon Righley
Simon Righley

Reputation: 4969

C++ template function on a STL container

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

Answers (2)

utnapistim
utnapistim

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:

  • define your function interface in terms of iterators, not of container. One of the greatest strengths of the std:: library is that is separates container logic (how do you get iterators and advance them) from the algorithm you apply on the iterators (in this case, 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

ForEveR
ForEveR

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

Related Questions