Changing variable name inside a loop

后端 未结 3 355
误落风尘
误落风尘 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 14:58

    You're misunderstanding C++ if you try to "rename a variable".

    C++ is a compiled language in which the names of the variables only exist in your source code as a means of handling them, but not in the compiled program.

    You hence can't also create a variable with a specific name at runtime -- variable names simply don't exist then.

    You probably want some kind of container that maps values to keys, think of a dictionary, where you can say "for this integer value 12, I store the string monkey" or so. Have a look at std::map.

    Now, you're really not making much sense right now; and try to do things that aren't really the way C++ works for anyone who learned it in a ordered manner. I'd really recommend getting a C++ book or tutorial and start with that. It's going to turn out to safe you a lot of time! Here's a list of recommended C++ books and ressources.

    0 讨论(0)
  • 2021-01-29 15:03

    You can't. It's not possible in C++.

    To declare and initialize a variable in each iteration is however possible:

    for (int i = 0; i != 10; ++i) {
            int var = i; // Declare 'var' and assign value of 'i' to it.  
    }                    // 'var' object goes out of scope and is destroyed
    

    Names are visible from the point where they are declared until the end of the scope in which the declaration appears. Names have scope and Objects have lifetimes.

    0 讨论(0)
  • 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 <map>
    #include <string>
    #include <sstream> //for int to string conversion
    
    std::string stringify(int val)
    {
      std::stringstream ss;
      ss << n;
      return ss.str();
    }
    
    int main()
    {
      std::map<std::string, int> 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;
    }
    
    0 讨论(0)
提交回复
热议问题