4

我已经设法了解了 C++ 的一些功能能力(for_each、映射函数、使用迭代器...),但是用于接收通用容器和迭代器的模板和函数参数列表的构造仍然让我望而却步。我有一个实际的例子,希望有人可以为我说明:

采用以下函数来处理传入的 std::vector 并构建一个进程的许多数据点/迭代的运行总数:

/* the for-loop method - not very savvy */
void UpdateRunningTotal (int_vec& total, int_vec& data_point) {
  for (int i = 0; i < V_SIZE; i++) {
    total[i] += data_point[i];
  }
}

typedef int_vec std::vector<int>;
int_vec running_total (V_SIZE, 0);  // create a container to hold all the "data points" over many iterations
/* further initialization, and some elaborate loop to create data points */

UpdateRunningTotal (running_total, iteration_data);
/* further processing */

上面的工作,但我更愿意有一个函数来接受迭代器并执行这个求和。更好的是,有一个类型推导的通用参数列表,而不是指定容器类型,即:

UpdateRunningTotal (iteration_data.begin(), iteration_data.end(), running_total.begin());

在这一点上我真的很迷茫,需要一些指导来找到如何定义模板和参数列表以使函数通用。模板和函数定义会是什么样子?我已经熟悉使用 STL 功能执行此特定任务的方法 - 我正在寻找通用函数/模板定义的说明。

4

2 回答 2

7

你可以使用std::transformand std::plus

std::transform(iteration_data.begin(), iteration_data.end(),
                running_total.begin(), iteration_data.begin(), std::plus<int>());

在您的功能中,这将是:

template <typename Iter1, typename Iter2>
void UpdateRunningTotal(Iter1 pBegin, Iter1 pEnd, Iter2 pBegin2)
{
    typedef typename std::iterator_traits<Iter1>::value_type value_type;

    std::transform(pBegin, pEnd, pBegin2, pBegin, std::plus<value_type>());
}
于 2010-06-07T17:40:57.843 回答
1

好吧,我可以给你一个函数签名,你必须填写正确的实现,因为你的规范现在对我没有意义。


template < typename InputIterator, typename OutputIterator >
?? UpdateRunningTotal(InputIterator beg, InputIterator end, OutputIterator dest)
{
}
于 2010-06-07T17:43:16.200 回答