Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 730
DreamCodeer Avatar asked Dec 27 '11 06:12

DreamCodeer


People also ask

Can double be a variable name?

All real numbers are floating-point values. A variable can be declared as double by adding the double keyword as a prefix to it. You majorly used this data type where the decimal digits are 14 or 15 digits.

Can you print a variable name in C?

How to print and store a variable name in string variable? In C, there's a # directive, also called 'Stringizing Operator', which does this magic. Basically # directive converts its argument in a string. We can also store variable name in a string using sprintf() in C.

Can we declare same variable name with same scope?

Do not use the same variable name in two scopes where one scope is contained in another. For example, No other variable should share the name of a global variable if the other variable is in a subscope of the global variable.

Can you use a string as a variable C++?

One of the most useful data types supplied in the C++ libraries is the string. A string is a variable that stores a sequence of letters or other characters, such as "Hello" or "May 10th is my birthday!". Just like the other data types, to create a string we first declare it, then we can store a value in it.


2 Answers

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.

like image 131
Mat Avatar answered Oct 01 '22 22:10

Mat


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.

like image 33
Nicol Bolas Avatar answered Oct 01 '22 21:10

Nicol Bolas