Choosing Array based on a trigger/if/variable
Mar 7, 2014 at 11:25pm UTC
Is it possible to have it pick what array to use based on a variable or trigger?
Something like:
1 2 3 4
string array
If (input.length() == 3)
{
array = PT2 //where PT2 is the name of the array to be used
Basically I just want to know if you can designate an array to use by using a string or something to hold the array name and use that string before []'s like you would while dealing with arrays.
Mar 7, 2014 at 11:27pm UTC
You could use a std::map.
something like
std::map<std::string,std::string *> map;
depending on type of array the value would change from string to int or w.e
http://www.cplusplus.com/reference/map/
Or you could use some sort of 2d container/array
Mar 7, 2014 at 11:32pm UTC
And having no knowledge of pointers sucks. ugh
Mar 7, 2014 at 11:37pm UTC
The pointer would just have the address of the array. So it would be something like:
1 2
int array[2] = { 1, 2 };
int *ptr = array; //arrays are special so the first element is the address
Then you can access the elements like a normal array
1 2 3 4
ptr[0] = 3;
ptr[1] = 4;
//array[0] == 3
//array[1] == 4
or you can access it like an offset pointer and dereference
1 2 3 4
*ptr = 5;
*(ptr+1) = 6;
//array[0] == 5
//array[1] == 6
Mar 8, 2014 at 12:05am UTC
What about 2 dimensional arrays? (which i'm using, not just a theoretical question)
Mar 8, 2014 at 12:11am UTC
Well it all depends on what you are trying to accomplish.
You could theoretically do something like:
1 2 3 4 5 6 7 8 9 10
int array[2][2] = { {0,1}, {2,3} }; //array 0 == option 1
//array 1 == option 2
[code]
int option;
std::cout << "Please enter an option(1,2): " ;
std::cin >> option;
std::cout << array[option-1][0] << std::endl;
Topic archived. No new replies allowed.