I have an assignment and the question is "write a function that creates a vector of user-given size M using new operator"
Code:
#include <iostream>
#include <vector>
int main()
{
int user_size;
std::cin >> user_size;
int *p = new std::vector<int> g5(user_size);
delete p;
return 0;
}
pls give me any advice how can I improve the code(obviously my knowledge improves too) and this code doesn’t feel right to me.
>Solution :
It’s unclear, what is meant here by vector. Moreover, the assignment says nothing about the type of the data. If vector is meant to be an array of M then the following
int*array = new int[M];
is the appropriate command (here assuming int as data type). In this case, you will need to delete the array later using the delete[] rather than plain delete, i.e.
delete[] array;
On the other hand, if vector refers to std::vector, then
std::vector<int> *pvec = new std::vector<int>(M);
is appropriate. However, this is really bad code, as std::vector under the hood allocates its data using new anyway, implying that this type of code generates a double reference and unnecessary memory allocation. Now you must use plain delete for destroying the object:
delete pvec;