无需复制和粘贴即可重用嵌套循环
假设我有这个嵌套循环
for (int a=1; a<MAX_A; ++a)
for (int b=1; b<MAX_B; ++b)
for (int c=1; c<MAX_C; ++c)
{
do_something(a, b ,c);
}
我在我的代码的各个部分重用了这个循环,改变了函数 do_something
.每次前三行都重写很无聊.例如,在 python 中,我会创建一个生成器来返回一个迭代器 (1, 1, 1), (1, 1, 2), ...
或类似 itertools.product代码>.
and I reuse this loop in various part of my code, changing the function do_something
. It's quite boring to rewrite every time the first three lines. In python for example I would created a generator to return an iterator (1, 1, 1), (1, 1, 2), ...
or something like itertools.product
.
在 c++ 中,我想到的唯一解决方案是定义一个宏.更好的东西?e
In c++ the only solution I've in mind is to define a macro. Something better?e
推荐答案
使用模板:
template<typename Func>
inline void do_something_loop(Func f)
{
for (int a=1; a<MAX_A; ++a)
for (int b=1; b<MAX_B; ++b)
for (int c=1; c<MAX_C; ++c)
{
f(a, b ,c);
}
}
可以使用任何匹配签名的函数指针或函数对象调用,例如:
This can be called with any function pointer or function object that matches the signature, e.g.:
void do_something(int a, int b, int c) { /* stuff */ }
do_something_loop(do_something);
或者用函数对象:
struct do_something
{
void operator()(int a, int b, int c) { /* stuff */ }
};
do_something_loop(do_something());
或者,如果您的编译器支持 C++11,即使使用 lambda:
Or if your compiler supports C++11, even with a lambda:
do_something_loop([](int a, int b, int c) { /* stuff */ });
请注意,您也可以将 f
参数声明为带有签名 void(*f)(int,int,int)
的函数指针,而不是使用模板, 但这不太灵活(它不适用于函数对象(包括 std::bind 的结果)或 lambdas).
Note that you could also declare the f
parameter as a function pointer with the signature void(*f)(int,int,int)
instead of using a template, but that's less flexible (it won't work on function objects (including the result of std::bind) or lambdas).
相关文章