c++ - 很多变量,没有嵌套循环的最佳方法

标签 c++ nested-loops cartesian-product

我在代码设计方面需要一些帮助和指导。我想运行多个变量设置为多个值的测试,而不创建疯狂数量的嵌套循环。我得到了一个包含各种变量的结构(例如仅三个整数,但实际交易将包含更多变量,包括 bool 值、 double 值等):

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

结构被传递到测试函数中。

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

我想对设定范围内的所有变量、变量的所有组合运行测试。一种方法是为每个变量创建一个循环:

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

但这似乎效率低下,并且随着变量数量的增加而变得难以阅读。实现这一目标的优雅方法是什么?一个症结是变量在未来会发生变化,删除一些变量,添加新的变量等等,因此一些解决方案在每个变量发生变化时不重写循环是更可取的。

最佳答案

range-v3 ,您可以使用 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);
}

关于c++ - 很多变量,没有嵌套循环的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253633/

相关文章:

c++ - 数组的名称是右值吗?

java - Java中无需排序即可查找众数和众数频率

java - 嵌套 For 循环数组搜索

排除对称结果的 PySpark 交叉连接

python - itertools 产品使用太多内存

c++ - 我应该怎么做才能获得 'dynamic' 数组的大小?

c++ - 如何为基于 ROM 的程序预初始化内存数据结构?

c++ - 结构和对象创建

php - 使用 mysql php 构建 JSON 并嵌套 while 导致内存分配耗尽错误

sql - 叉积(交叉连接,笛卡尔积)和自然连接的区别