Using the loop integer to define variables: c++

前端 未结 3 1366
忘掉有多难
忘掉有多难 2021-01-16 12:09

I have a for-loop which runs over i. For every iteration, I wish that it creates a variable with the name var_i i.e if my loop runs over i=0<

相关标签:
3条回答
  • 2021-01-16 12:51

    You can't create variables at runtime. Use std:vector instead so you'll get var[0], var[1], etc.

    0 讨论(0)
  • 2021-01-16 13:00

    You can't, variable names must be known at compile-time. You can't create new variable names at run-time.

    An alternative is to have a std::map or a std::vector if your variables are continuous.

    std::map<int,int> int_;
    std::vector<int> vint_;
    vint_.resize(5);
    for ( int i = 0 ; i <= 4 ; i++ )
    {
       int_[i] = i;
       vint_[i] = i;
    }
    

    Your variables would be int_[0] or vint_[0] through int_[4] or vint_[4].

    0 讨论(0)
  • 2021-01-16 13:11

    You can also use an array of the required size and initialize it with a default value in the loop

    int var[4];
    for(int i=0; i < 4; i++){
        var[i] = 0;
    }
    
    0 讨论(0)
提交回复
热议问题