-
Char Indexing arrays
I am trying to create an array of objects where the index value is a string instead of an int, for example instead of:
Code:
array[0] = object1;
array[1] = object2;
I would like to have:
Code:
array[A2] = object1;
array[E4] = object2;
Please can anyone tell me whether this is possible. I know the syntax for creating a usual array:
ClassName arrayname[arraysize]
But what would be the syntax to create an array with the string indexes.
Thank you for any help you can provide.
Dutch
-
-
Array indexes have to be numbers,
if you want to make the numbers more meaningful in the program you can use #define or const , but you can't index arrays with strings ( but why would you want to anyway? ).
#define THIRD_THING 2
or
const int THIRD_THING = 2;
int array[3];
array[THIRD_THING] = 49;
-
Look into the map and multimap objects. For the sake of argument, let's assume that your object1 and object2 variables are integer's, you could create such an array as you are talking about by doing this:
Code:
#include <map>
#include <string>
using std::string;
using std::map;
map<string,int> MyArray;
int object1, object2;
MyArray["A2"] = object1;
MyArray["E4"] = object2;
-
You can't, array indexes have to be int.