Reputation: 127
I want to define variables whose names depend on the values of other variables, such as
for (int i = 0; i < 5; i++) {
int v_i = 2 * i
}
std::cout << v_3; // output: 6
or
int m;
std::cin >> m; // m = 42
int v_m = 10;
std::cout << v_42; // output: 10
Of course, these examples do not work but instead just create variables with the names v_i
or v_m
, treating i and m as characters.
How could I accomplish this?
Upvotes: 1
Views: 57
Reputation: 4093
You can use an associative map. It lets you associate a key with a value and then access a value from that key.
http://www.cplusplus.com/reference/map/map/
Example:
int main ()
{
std::map<char,int> test;
test['a']=10;
test['b']=30;
test['c']=50;
test['d']=70;
std::cout << test['a'] << std::endl; //prints 10
}
In your case, it would be a map<int, int>
Maps are also known as Dictionnary in some other languages.
Upvotes: 1