Delete parts of the dynamic array and produce other

I need to have a dynamic array, so I need to allocate the required amount of memory through a pointer. What makes me think about what is a good solution is that C ++ has the ability to do something like:

int * p = new int[6];

which allocates the required array. I need, then, I want to grow some parts of this array. Example (n erroneous):

int *p1 = &p[0];
int *p2 = &p[2];
int *p3 = &p[4];
// delete positions p[2], p[3]
delete [] p2;
// create new array
p2 = new int[4];

I do not know how to achieve this behavior.

EDIT: std::vectordoes not work for me, since I need the time to insert / delete items in kproportion to the number k, not the number of items stored in std::vector.

, , , . , ( "", "" ).

+2
4

, std::vector:

std::vector<int> v(6);         // create a vector with six elements.
v.erase(v.begin() + 2);        // erase the element at v[2]
v.insert(v.begin() + 2, 4, 0); // insert four new elements starting at v[2]

, , , std::vector. , ++ .

+8

STL ++, vector , .

+1

. std::vector .

+1

there is another option besides std::vectorthere std::deque, which works in much the same way, but is slightly more efficient when inserting pieces in the middle. If this is not enough for you, you can get mileage using a collection of collections. You will have to do a bit more work by gaining random access to the work (maybe write a class to wrap it all up.

+1
source

Source: https://habr.com/ru/post/1766889/


All Articles