How to use a string as a variable name in C++?

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.

Share:
13,124

Related videos on Youtube

DreamCodeer
Author by

DreamCodeer

Updated on June 04, 2022

Comments

  • DreamCodeer
    DreamCodeer almost 2 years

    Possible Duplicate:
    Convert string to variable name or variable type

    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.? Thanks in advance.

    • Admin
      Admin over 12 years
      You ... don't! Even in languages that do support this ... think twice.
    • Ed S.
      Ed S. over 12 years
      No, you think you do, but you don't. There are better ways to solve your problem, whatever it may be.
    • Nicol Bolas
      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
      Karl Knechtel over 12 years
      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.
  • DreamCodeer
    DreamCodeer over 12 years
    Thanks. Dont want to make the code more complex.