I want to know if a variable content can be used as variable name. Example below:
int a;
string b = "nombre";
I'm asking if "nombre" can replace "a" as variable name.
CodePudding user response:
If you want to be able to map strings to numeric values, you could create a map object:
#include <unordered_map>
#include <string>
#include <iostream>
int main()
{
std::unordered_map<std::string, int> vars {
{ "nombre", 5 },
{ "otro_nombre", 3 },
};
std::cout << vars["nombre"] << ' ' << vars["otro_nombre"]
<< " = " << (vars["nombre"] vars["otro_nombre"]);
}
This yields:
5 3 = 8
on the output stream. See it working on GodBolt.
CodePudding user response:
You can use references to create an alias for an already existing variables, if this is what you're looking for.
int a = 5;
int& nombre = a; //nombre is now an alias for a