Search code examples
c++arraysarray-key

C++ get array key in constructor of array of a custom class/struct?


If I have a simple class like this:

class MyClass
{
    MyClass(){}
    ~MyClass(){}
public:   
    int myArrayKeyValue;
};

And later, I create an array of these classes:

MyClass testing[10];

How, in the constructor, would I access the array key so I can set the myArrayKeyValue appropriately for each element of the array? So that I get this:

testing[0].myArrayKeyValue = 0;
testing[1].myArrayKeyValue = 1;
testing[2].myArrayKeyValue = 2;
testing[3].myArrayKeyValue = 3;
etc...

Is it possible to accomplish this in the constructor? Or do I have to just loop through the array and assign the values manually?


Solution

  • Is it possible to accomplish this in the constructor?

    No.

    Or do I have to just loop through the array and assign the values manually?

    Yes. Although you might be able to redesign so that you don't need the knowledge of the index inside and outside of these instances.

    Possible alternatives would include:

    • an associative container like map<int, MyClass>
    • a set<MyClass> with the key value being the ordering criteria