I want to make a dynamic array of foo, with the number of items being x. Arguments y and z are to be passed to the constructor of the item foo. I was hoping to do something similar to:
Foo* bar = new Foo(y, z)[x];
However that produced the following compiler error:
error: expected `;' before '[' token
So after speaking with an experienced friend, he gave me this, which he admitted was a lazy way of doing it, but it works. I was wondering, is there a better/proper way?
Foo* bar = (Foo*) new int[x];
for (int i = 0; i < x; i++) {
bar[i] = Foo(y, z);
}
“I want to make a dynamic array” So use a
std::vector, it exists for a reason.This creates a dynamic array with
xelements initialized tofoo(y, z).The above makes copies of the second parameter,
xtimes. If you want to generate values for thevector, usegenerate_n:You replace
...with a function or functor to call, that returns a value. Generally you make a functor:Giving:
If your compiler supports C++0x, you can take advantage of lambda’s. These do the same thing, except they keep the code concise and localized: