Changing variable name inside a loop

后端 未结 3 354
误落风尘
误落风尘 2021-01-29 14:20

I\'m trying to create a loop that will will create a new variable but also change the name of the variable, such as increasing in value, automatically. Not sure if this is possi

3条回答
  •  执笔经年
    2021-01-29 15:03

    The closest thing to "renaming" in C++ would be declaring a reference of the "old named" variable with the new name.

    int a = 2;
    int &b = a;
    //you can now call either `b` or `a` to get the value
    

    Creating new variables on the fly is not possible. The correct insert any compiled language name here way of doing it is by pushing values into a container (array, map, stack..etc). With maps, you can do something similar to what you want, but it's different one only "maps" a string to a value.

    #include 
    #include 
    #include  //for int to string conversion
    
    std::string stringify(int val)
    {
      std::stringstream ss;
      ss << n;
      return ss.str();
    }
    
    int main()
    {
      std::map values;
      for (int i = 0; i < 10; i ++){
        values[stringify(i)] = i*100;
      }
      std::cout << values["1"]; // prints 100
      std::cout << values["9"]; // prints 900
      return 0;
    }
    

提交回复
热议问题