0

我正在使用模板实现 Reduce 功能。Reduce fn 将两个参数的函数累积应用于 STL 容器的项目,从 begin() 到 end(),以将序列减少为单个值。

 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)
}

我的 C++ 代码:

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);

}

欢迎任何意见。

谢谢 !

4

2 回答 2

2

首先让我观察一下:不要使用异常规范。无论如何,它们在 C++11 中已被弃用。

我建议使用accumulate来完成这项工作(并且强烈考虑使用两个迭代器Reduce而不是一个带容器的迭代器):

Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
    return std::accumulate(c.begin(), c.end(), typename Container::value_type());
}
于 2013-09-03T16:47:04.887 回答
0

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.

于 2014-11-14T14:14:13.137 回答