tags:

views:

89

answers:

5

When dealing with multidimensional arrays is it possible to assign two different variable types to the array... For example you have the array int example[i][j] is it possible for i and j to be two completely different variable types such as int and string?

+1  A: 

No, you can only use integer types as indices.

kotlinski
So you would have to use two separate arrays to do something like student_name and score
Alec
@Alec: what exactly are you trying to do? Do you want `array[name][score]` to access some third piece of data?
JoshD
Blah, what i said made no since.. Sorry, I am trying to do that but gave a very poor example of what i'm trying to do.
Alec
+2  A: 

No, C++ only allows integer types (ex: int, long, unsigned int, size_t, char) as indexes.

If you want to index by a string, you could try std::map<std::string,mytype> but it gets complicated trying to extend that to two dimensions.

Mark Ransom
+2  A: 

No, but you could use std::maps.

karlphillip
+3  A: 

No. That's not possible. You may want to look into using the STL map.

JoshD
+6  A: 

Sounds like you're looking for:

std::vector<std::map<std::string, int> > myData1;

or perhaps:

std::map<int, std::map<std::string, int> > myData2;

The first would require you to resize the vector to an appropriate size before using the indexing operators:

myData1.resize(100);
myData1[25]["hello"] = 7;

...while the second would allow you to assign to any element directly (and sparsely):

myData2[25]["hello"] = 7;
Drew Hall
Nice example. +1
JoshD
Note that the first form will be more efficient than the second, but efficiency isn't always everything. The second has big advantages in usability and extensibility. Also note that with `map` if you try to index something that doesn't exist, it will create it automatically with a default value.
Mark Ransom