我正在使用模板实现 Reduce 函数。这 Reduce fn 将两个参数的函数累积应用于 一个 STL 容器,从 begin() 到 end(),以便将序列减少为 单一值(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)
}
我的 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);
}
欢迎任何意见。
谢谢!
最佳答案
首先让我观察一下:不要使用异常规范。无论如何,它们在 C++11 中已被弃用。
我建议使用 accumulate
来完成这项工作(并且 强烈 考虑使用两个迭代器 Reduce
而不是一个容器) :
Reduce(const Container& c, Function fn) throw (NotEnoughElements)
{
return std::accumulate(c.begin(), c.end(), typename Container::value_type());
}
关于c++ - 通过 C++ 实现容器元素总和的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597203/