Instantiate an array of objects

Hello,

I want to create an array of object of class MyClass, but with different parameters for the constructor. My best move is:
1
2
3
4
MyClass * my_array;
my_array = new MyClass[2];
my_array[0] = new MyClass(0);
my_array[1] = new MyClass(1);

There is no better way?!

MyClass have an operator []. But to call it, I must do:
 
(*my_array[0])[i]

Again, is there a better syntax?

Thank you.
Last edited on
If your objects are copyable:

1
2
3
vector<MyClass> vec;
vec.push_back(MyClass(0));
vec.push_back(MyClass(1));
If there is no discernible order to the parameters, then it needs to be done manually. i.e.
1
2
3
4
5
6
array[0]=new MyClass(0);
array[1]=new MyClass(0);
array[2]=new MyClass(456);
array[3]=new MyClass(159);
array[4]=new MyClass(485);
array[5]=new MyClass(-2000);


However, if there is a relationship between the parameters (using your example: if the parameter equals the index), you can use a for-loop of some sort.

1
2
for(int i=0;i<5;i++)
   my_array[i]=new MyClass(i);


Or something.
@Athar:
Thank you! I have a lot of reading with vectors, lists and deques. I'm sure I will find what I need.

@Wasabi:
My problem was the pointless call to the default constructor by my_array = new MyClass[2];. Sorry for my imprecision and thank you anyway.
Topic archived. No new replies allowed.