问题
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