重复使用嵌套循环而不复制和粘贴 [英] reuse nested loops without copy and paste

查看:158
本文介绍了重复使用嵌套循环而不复制和粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个嵌套循环



pre $ for(int a = 1; a< MAX_A; ++ a)$对于(int c = 1; c< MAX_C; ++ c)
{
do_something(a,b),b $ b for(int b = 1; b




我在代码的不同部分重用了这个循环,改变了函数 do_something 。重写前三行是很无聊的事情。在python中,例如,我将创建一个生成器以返回一个迭代器(1,1,1),(1,1,2),... 或类似于 itertools.product



在c ++中,唯一的解决方案就是定义一个宏。有些东西比较好?

解决方案

使用模板:

 模板< 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);




$ b $ p $可以用任何函数指针或函数对象(例如:
$ b $ pre $ 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:

  do_something_loop([](int a,int b,int c){/ * stuff * /}); 

请注意,您也可以声明 f 参数作为一个函数指针与签名 void(* f)(int,int,int)而不是使用模板,但是这不灵活函数对象(包括std :: bind的结果)或lambda表达式)。


Suppose I've this nested loop

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);
    }

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.

In c++ the only solution I've in mind is to define a macro. Something better?e

解决方案

Use templates:

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);

Or with a function object:

struct do_something
{
    void operator()(int a, int b, int c) { /* stuff */ }
};

do_something_loop(do_something()); 

Or if your compiler supports C++11, even with a lambda:

do_something_loop([](int a, int b, int c) { /* stuff */ });

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).

这篇关于重复使用嵌套循环而不复制和粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆