Home > Software design >  C generating a variable number of nested FOR-loops
C generating a variable number of nested FOR-loops

Time:10-17

I have a struct containing a vector of elements:

struct SomeStruct
{
    std::vector<Element> vec;
};

each Element contains a container:

struct Element
{
    Container m_container;
};

The vector can contain 3, 4 or 5 Elements. This is guaranteed.

If there are 3 items, the next stage contains a series of 3 nested for loops (see below). A vector with 4 elements required 4 loops, 5 -> 5 loops etc. There will only be 3, 4 or 5 loops.

I have to omit some code but the logic within the loops concludes with multiplying the doubles together and calculating a minimum. So the inner-most loop needs access to the local variables from the earlier loops.

for(const auto& x : vec[0].m_container)
{
    const double some_calc = some_func(x);

    for(const auto& y : vec[1].m_container)
    {
        const double some_calc_2 = some_func(y);

        for(const auto& z : vec[2].m_container)
        {
            const double some_calc_3 = some_func(z);

            // TODO need a way to generate 4th and 5th loops if required

            // Logic processing data from the 3 loops
            const double a_calculation = some_calc * some_calc_2 * some_calc_3;
            double a_min = some_calc;
            a_min = std::min(a_min, some_calc_2);
            a_min = std::min(a_min, some_calc_3);
        }
    }
}

Is there a way I can automate/generate these nested FOR Loops, depending on the size of the vector? I was thinking of something templated like this:

if(struct.vec.size() == 3)
{
    the_answer<3>(struct.vec);
}
else if(struct.vec.size() == 4)
{
    the_answer<4>(struct.vec);
}
else
{
    the_answer<5>(struct.vec);
}

CodePudding user response:

This can be done with a recursive function.

void loop(const std::vector<Element>& vec, size_t idx) {
  if (idx   1 == vec.size()) {
    for (const auto& z : vec[idx].m_container) {
      const double some_calc = some_func(z);

      // Logic processing data from the innermost loop
      const double a_calculation = some_calc * some_calc_2 * some_calc_3;
      double a_min = some_calc;
      a_min = std::min(a_min, some_calc_2);
      a_min = std::min(a_min, some_calc_3);
    }
  } else {
    for (const auto& z : vec[idx].m_container) {
      const double some_calc = some_func(z);
      loop(vec, idx   1);
    }
  }
}

Somewhere start

loop(vec, 0);

CodePudding user response:

You can solve solve this problems most of the times with recursion. so

void loop(int n,const vector<double>& vec, vector<double> outer_vars){
     if (n!=vec.size()){
         for(const auto& z : vec[n]){
             outer_vars.push_back(some_func(z));
             loop(n 1,vec,outer_vars);
         }
     }
}
  • Related