c++ - 通过 C++ 实现容器元素总和的模板函数

标签 c++ templates stl sum

我正在使用模板实现 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/

相关文章:

c++ - 结合来自 ttf 和背景纹理的渲染器文本的 OpenGL 错误

c++ - 如果 cpp 中的数据类型条目不正确,如何允许多个输入?

c++ - 使用 gethostbyname() 提取 IP 数据

c++ - C++中如何在另一个模板类中使用一个模板类

c++ - 在 C++ 中选择重载模板函数时的优先级

algorithm - 平衡绳的串联复杂度是多少?

c++ - 将 vector 添加到 vector

c++ - 从 3d 模型截取屏幕截图

c++ - STL:使用 ptr_fun 为 "const T &"类型调用 bind2nd

c++ - 拆分给定类型的参数包