user2420472
user2420472

Reputation: 1177

implement a template function for container's elements sum by C++

I am implementing the Reduce function using templates. The Reduce fn applies a function of two arguments cumulatively to the items of an STL container, from begin() to end(), so as to reduce the sequence to a single value.

 For example, Reduce(<list containing 1,2,3,4,5>, std::plus<int>()) should calculate ((((1+2)+3)+4)+5)

class NotEnoughElements {};

template <typename Container, typename Function>
typename Container::value_type
Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
   FILL HERE (recursion)
}

My C++ code:

Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
    if (c.begin() == c.end() || c.size() < 1)
            throw(NotEnoughElements);
    Container::iterator itr = c.begin(); 
    Container::iterator itr_end = c.end(); 
    Container::value_type  sum = 0;
    Fn(itr, itr_end, sum);
    Return sum;
}

void Fn(Container::const_iterator itr,  Container::const_iterator itr_end, Container::value_type& sum)
{
  sum += *itr;
  if (itr == itr_end || itr+1 == itr_end)
     return ;
  Fn(++itr, itr_end, sum);

}

Any comments are welcome.

Thanks !

Upvotes: 0

Views: 755

Answers (2)

Yongwei Wu
Yongwei Wu

Reputation: 5582

I have implemented Reduce like follows:

template <typename Function, typename Container>
typename Container::value_type
Reduce(Function reducefn, Container list)
{
    return std::accumulate(begin(list), end(list),
                           typename Container::value_type(), reducefn);
}

template <typename Function, typename Container>
typename Container::value_type
Reduce(Function reducefn, Container list,
       typename Container::value_type initial)
{
    return std::accumulate(begin(list), end(list), initial, reducefn);
}

For your reference.

Upvotes: 0

Mark B
Mark B

Reputation: 96291

First let me just observe: Don't use exception specifications. They're deprecated in C++11 anyway.

I would suggest using accumulate to do the work (and do strongly consider using a two iterator Reduce rather than one taking a container):

Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
    return std::accumulate(c.begin(), c.end(), typename Container::value_type());
}

Upvotes: 2

Related Questions