Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating vector using new operator

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading