很多变量,没有嵌套循环的最佳方法 [英] Lots of variables, best approach without nested loops

查看:58
本文介绍了很多变量,没有嵌套循环的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些有关代码设计的帮助和指导.我想在多个变量设置为多个值的情况下运行测试,而不会创建大量的嵌套循环.我得到了一个结构体,它包含这样的各种变量(仅以三个整数为例,但实际情况将包含更多,包括布尔值、双精度值等):

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.

推荐答案

With range-v3,您可以使用 cartesian_product 视图:

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

这篇关于很多变量,没有嵌套循环的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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