繁体   English   中英

您可以在C ++中动态创建for循环吗?

[英]Can you create for loops dynamically in C++?

代码中注释了我的问题,有什么方法可以实现我想要的?

#include <iostream>

int main()
{
    std::cin >> n_loops; //I want to specify the number of nested loops and create new variables dynamically:
    // variables names: x1, x2, x3, ... x(n_loops)
    // if n_loops is 3, for example, I want this code to be executed.
    for (int x1 = 0; x1 < 10; x1++)
        for (int x2 = 0; x2 < 10; x2++)
            for (int x3 = 0; x3 < 10; x3++)
            {
                std::cout << x1 << ", " << x2 << ", " << x3 << std::endl;
            }
    std::cin.get();
}

不是直接的,但是您可以实现“里程表样式”的行为,如下所示:

#include <iostream>
#include <vector>

static bool AdvanceOdometer(std::vector<int> & counters, int idxToIncrement, int counter_max)
{
    if (++counters[idxToIncrement] == counter_max)
    {
       if (idxToIncrement == 0) return false;  // signal that we've reached the end of all loops

       counters[idxToIncrement] = 0;
       return AdvanceOdometer(counters, idxToIncrement-1, counter_max);
    }
    return true;
}

int main()
{
   int n_loops;
   std::cin >> n_loops;

   std::vector<int> counters;
   for (size_t i=0; i<n_loops; i++) counters.push_back(0);

   const int counter_max = 10;  // each "digit" in the odometer should roll-over to zero when it reaches this value
   while(true)
   {
      std::cout << "count: ";
      for (size_t i=0; i<n_loops; i++) std::cout << counters[i] << " ";
      std::cout << std::endl;

      if (AdvanceOdometer(counters, counters.size()-1, counter_max) == false) break;
   }
   return 0;
}

可以完全重复地表达相同的概念(一些读者可能会发现更清晰,并且避免了递归调用可能造成的边际效率低下)可以像下面这样:

#include <iostream>
#include <string>           // std::stoi
#include <vector>           // std::vector
using namespace std;

auto advance( vector<int> & digits, int const radix )
    -> bool      // true => advanced without wrapping back to all zeroes.
{
    for( int& d : digits )
    {
        ++d;
        if( d < radix ) { return true; }
        d = 0;
    }
    return false;
}

auto main( int n_args, char** args )
    -> int
{
   int const n_loops = stoi( args[1] );
   std::vector<int> digits( n_loops );

   const int radix = 10;

   do
   {
      for( int i = digits.size() - 1; i >= 0; --i )
      {
          cout << digits[i] << " ";
      }
      cout << std::endl;
   } while( advance( digits, radix ) );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM