5

How 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?

10
  • You mean to dynamically make a vector variable that has the name "BF_vector_hari" similar to php's double $? Commented Dec 27, 2011 at 6:21
  • 6
    You ... don't! Even in languages that do support this ... think twice. Commented Dec 27, 2011 at 6:22
  • 4
    No, you think you do, but you don't. There are better ways to solve your problem, whatever it may be. Commented Dec 27, 2011 at 6:24
  • 4
    @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. Commented Dec 27, 2011 at 6:31
  • 3
    It'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. Commented Dec 27, 2011 at 7:10

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.