Reputation: 37
Let's say we have a couple arrays called "one", "two", and "three". Is there any way to access/modify the arrays using a string that contains the name of the array? For example,
int one[n];
int two[n];
int three[n];
string str = "one";
// str can be "one", "two", or "three"
// I wanna access/modify whatever array that str is the name of
Upvotes: 1
Views: 93
Reputation: 490158
Yes it's possible. But also yes, you'll have to do write the code to map from the name as a string to the array you want that name to refer to.
A simple version would be to use an std::unordered_map
for the task:
std::vector<int> one, two, three;
std::unordered_map<std::string, std::vector<int> &> names {
{ "one", one },
{ "two", two },
{ "three", three }
};
std::string arrayName;
std::cin >> arrayName;
auto pos = names.find(arrayName);
if (pos == names.end())
std::cerr << "name not found\n";
else {
auto & currentArray = pos->second;
// do something with the selected vector:
currentArray.push_back(1);
}
This isn't something that arises terribly often, but it can at times. One obvious possibility is when you're writing an interpreter for some programming language.
In such a case, you'll typically have a slightly different structure though. You'll have something like this:
class Integer { /* ... */ };
class String { /* ... */ };
// ...
std::variant<Integer, String /* ... */ } Variable;
std::unordered_map<std::string, Variable> symbol_table;
So with this, we specify a class to model each type in the target language, and then have a symbol table mapping from names to objects.
But there are also a few languages that only really have variables of one type, and to the extent they support other types at all, it's by converting from that one type to whatever else on the fly, based on how they're used. In such a case, you'd probably store all your variables as objects of the same type.
Upvotes: 3
Reputation: 125007
Is there anyway to access/modify an array using a string that contains the name of the array?
No. Variable names are there for the benefit of the programmer; by the time the code is compiled and executed, a variable's name no longer exists.
Upvotes: 0