我正在使用模板实现 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);
}
欢迎任何意见。
谢谢 !