How to use a string as a variable name in C++?
13,124
Solution 1
You can't in C++.
One thing you can do is use a form of std::map<std::string, std::vector>
to store name to vector map.
Solution 2
You don't.
Variable names are a compile-time construct. The contents of a string are a run-time concept (string literals are slightly different, but those won't work either). Unless you write a specific mapping layer (which maps a string name to some object), you cannot just use a string as a variable name.
Or a type name for that matter.
Related videos on Youtube
Author by
DreamCodeer
Updated on June 04, 2022Comments
-
DreamCodeer almost 2 years
Possible Duplicate:
Convert string to variable name or variable typeHow to use the string value as a variable name in c++
string listName = "hari"; string vectorName = "BF_vector_"+listName; vector<string> vectorName; vectorName.push_back("Some Value");
How to use the string value("BF_vector_hari") of vectorName as a variable name of vector.? Thanks in advance.
-
Admin over 12 yearsYou ... don't! Even in languages that do support this ... think twice.
-
Ed S. over 12 yearsNo, you think you do, but you don't. There are better ways to solve your problem, whatever it may be.
-
Nicol Bolas over 12 years@EthanSteinberg: The terminology itself is the point. It bespeaks a fundamental misunderstanding of how C++ works. What he wants cannot be done as he wants it, specifically with dynamic variable names. You can create a mapping table, which is an object that maps names to objects, but it doesn't map them to variables.
-
Karl Knechtel over 12 yearsIt's amazing how many people independently come up with the desire to do this horrible, nonsensical thing... it makes me wonder if there's some fundamental failure in our educational materials to explain what variables really are.
-
-
DreamCodeer over 12 yearsThanks. Dont want to make the code more complex.