Lots of variables, best approach without nested loops

南笙酒味 提交于 2021-01-29 07:11:55

问题


I’m in need of some help and guidance on the design of my code. I want to run tests with multiple variables set to multiple values, without creating insane amounts of nested loops. I got a struct which holds various variables like this (only three integers as an example, but the real deal will hold a lot more, including booleans, doubles etc):

struct VarHolder
{
    int a;
    int b;
    int c;
    // etc..
    // etc..
};

The struct get passed into a test function.

bool TestFunction(const VarHolder& _varholder)
{
    // ...
}

I want to run the test for all variables ranging for a their set range, all combinations of the variables. One way is to create a loop for each variable:

for (int a = 0; a < 100; a++)
{
  for (int b = 10; b < 90; b++)
    {
      for (int c = 5; c < 65; c++)
        {
          //...
          //...

             //set variables
             VarHolder my_varholder(a, b, c /*, ...*/);
             TestFunction(my_varholder);
        }
    }
}

But this seems inefficient and gets unreadable fast as the amount of variables gets bigger. What is an elegant way to achieve this? One crux is that the variables will change in the future, removing some, adding new one’s etc. so some solution without rewriting loops for each variable as they change is preferable.


回答1:


With range-v3, you might use cartesian_product view:

auto as = ranges::view::ints(0, 100);
auto bs = ranges::view::ints(10, 90);
auto cs = ranges::view::ints(5, 65);
// ...
// might be other thing that `int`

for (const auto& t : ranges::view::cartesian_product(as, bs, cs /*, ...*/))
{
    std::apply(
        [](const auto&... args) {
            VarHolder my_varHolder{args...};
            Test(my_varHolder);
        },
        t);
}


来源:https://stackoverflow.com/questions/56253633/lots-of-variables-best-approach-without-nested-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!