Suppose in a code I want the user to specify an integer(say x) and then allocate those many consecutive cells in computer memory on which I do some kind of processing.
My question is is it “better” to allocate this memory as new double[x] or vector<double>(x).
I know that both methods seem to work fine ( i.e. compiles and runs at least in this teeny little code)
int x; int* p;
cout<<"Enter integer x:";cin>>x;
vector<double> v(x);
p=new double[x]
If you think the answer is using new then is it possible to somehow magically convert
the memory allocated via new into a vector? Because vectors would give me more power in manipulating the data.
It’s better to use
vectorwhenever you can because of the many advantages it provides (automatic memory management, bounds checking, etc).Also, to have the vector reserve a number of elements for you to use (i.e. allocate that many all at once in memory instead of eventually resizing up to it as you add elements), you can pass that number to the vector’s constructor:
Or if you’ve already created a vector, use
vector::resize:And no, there’s no way to tell a vector to use memory you’ve already allocated unless you use a custom allocator [R. Martinho Fernandes, comments].