In c++, I am attempting to create an array to store two different datatypes. Essentially, I want an ID and the actual datatype.
psuedocode:
array[int][myObj]
0, myObj1
1, myObj2
2, myObj3
I understand this is not how to declare an array. Is this functionality possible? Do I have to create a custom class with a struct?
It depends on how you want to use it. There’s a number of options that all have valid use-cases:
A simple array of myObj:
myObj array[]. This matches the example you’ve given because the associated ID of an object is simply the index of that object in the array. The first element has ID 0, second has ID 1, etc. However, for the sake of flexibility and good C++ style, you should really use eitherstd::vectororstd::array.If you want to associate each object with a fixed ID regardless of its position in the array (and possibly in other places too). You can use a
std::pair<int, myObj>to pair an integer to an instance of your object. You would use it like so:A similar alternative to this is to encapsulate the ID within your myObj class. However, this may not be appropriate in certain cases (ID is really not part of myObj, separate IDs may be used for the same object at any time).
If you need to be able to access the element in the array by its ID, you want an
std::map<int, myObj>. This will map integer IDs to the instances of myObj. Use it like so:Now you can access an element with, for example,
m[0]. If you want to speed up access time and don’t care about the elements being ordered, you could use astd::unordered_mapinstead