c++ - 你能在 C++ 中动态创建 for 循环吗?

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

关于c++ - 你能在 C++ 中动态创建 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210919/

相关文章:

c++ - 使用低级 WinAPI 调用的 C++ 中的 Windows 窗体自动化?

c++ - Unicode 字符 Visual C++

c++ - Win7 GLUT 窗口不接收事件

c++ - 与静态链接的功能混淆

c++ - 如何将 C/C++ python 模块与 PVTS 项目/VS 2013 解决方案集成

C++ std::find lambda 表达式

c++ - 保持 cpp 文件和头文件同步的最佳工作流程是什么?

C++ 自动函数返回?

c++ - 以下代码片段的算法复杂度

c++ - CMake with AUTOMOC 正在删除我的实现