(C++) auto create object / variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

(C++) auto create object / variable

i want to create variable / object with a specific pattern. example in python, i can write something like: num = 0 for (i in range(10)): auto = "var%d = %d" %(num, num) exec(auto) num+=1 so i have 10 variable now. unfortunately, c++ doesnt have a function like enum or exec. any idea? im stuck here.

31st Jan 2018, 8:35 AM
Kevin AS
Kevin AS - avatar
5 Answers
+ 4
You can do it with arrays, but the variable name do not really change You can allocate memory so that you have more space (like more integers) usable during runtime
31st Jan 2018, 3:21 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 4
you can overload string operator '%', but the problem will reside in the right part of the code. If num is not a primitive type (can be a wrapper of a primitive type), you'll have to override the ',' operator to store all the variables (maybe return a std::tuple) then use it with the operator '%' you did with the tuple you used. If you want to keep track of num so that it can be changed, use references
31st Jan 2018, 9:15 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 4
I read back the question, and indeed I made a mistake. You can't create variable names at runtime (you can though at compile time)
31st Jan 2018, 11:58 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
@baptiste im not understand. your point is, i need to overload string operator?
31st Jan 2018, 9:18 AM
Kevin AS
Kevin AS - avatar
0
yeah. what i mean is create variable at runtime. i hope i can find the answer :)
31st Jan 2018, 1:52 PM
Kevin AS
Kevin AS - avatar