重构“哑”函数转换为通用的STL风格与迭代器到容器 [英] Refactoring a "dumb" function into generic STL-style with iterators to containers
问题描述
我已经设法围绕一些C ++的功能性能力(for_each,映射函数,使用迭代器...),但是模板和函数参数列表的构造,用于接收通用容器和迭代器仍然逃避了我。我有一个实际的例子,我希望有人可以为我说明:
I've managed to wrap my head around some of C++'s functional capacities (for_each, mapping functions, using iterators...) but the construction of the templates and function argument lists for taking in generic containers and iterators still eludes me. I have a practical example I'm hoping someone can illustrate for me:
采取以下函数处理一个传入的std :: vector,并建立一个运行的许多数据 - 进程的点/迭代:
Take the following function that processes an incoming std::vector and builds a running total of many data-points/iterations of a process:
/* 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 */
上面的工作,一个函数,它接受迭代器并执行这个求和。更好的是,具有推导类型的通用参数列表,而不是指定容器类型,即:
The above works, but I'd much rather have a function that takes iterators and performs this summation. Even better, have a generic parameter list with the type deduced instead of specifying the container type, i.e.:
UpdateRunningTotal (iteration_data.begin(), iteration_data.end(), running_total.begin());
我真的在这一点上迷失了,需要一些指导才能找到如何定义模板参数列表使函数通用。模板和函数定义会是什么样子?我已经熟悉如何使用STL功能执行这个特定的任务 - 我正在寻找通用函数/模板定义的插图。
I'm really lost at this point and need a little guidance to find how to define the template and argument lists to make the function generic. What would the template and function definition look like? I'm already familiar with a way to perform this specific task using STL functionality - I'm looking for illustration of the generic function/template definition.
推荐答案
您可以使用 std :: transform
和 std :: plus
:
You could use std::transform
and std::plus
:
std::transform(iteration_data.begin(), iteration_data.end(),
running_total.begin(), iteration_data.begin(), std::plus<int>());
在您的函数中,它将是:
And in your function, that would be:
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>());
}
这篇关于重构“哑”函数转换为通用的STL风格与迭代器到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!