Reputation: 1
I have an array of sockets (pfd[nfd].fd). I also have an array of pointers (event_tracking* track[10]). If there comes a point in my code where I try and receive data from a socket that is closed I would like to remove that array element in both arrays and then shift the arrays to fill the empty spot.
for(j=1; j<nfd; j++) {
if(pfd[j].revents&POLLIN) {
char* p = track.receive_datagram();
if (p == 0) {
delete track[j-1];
//Delete element in pfd[nfd].fd
//Reorder elements of track array
//Reorder elements of pfd array
}
}
}
I know you can call the delete operator to call the destructor for track but I'm not sure how to reorder the elements in the array now that one is missing? Or how to delete and reorder the pfd array?
Any help would be appreciated! I can't find any examples of deleting and reordering arrays in my text.
Upvotes: 0
Views: 726
Reputation: 15134
Without changing your data structures, the solution is to copy each element after the one you remove over the previous element of the array. This is more efficient for a linked list. With an array allocated by new[]
, you would not reallocate anything, but you could resize a vector
.
Upvotes: 0
Reputation: 133567
A C++ solution should be to use a std::vector
or std::array
and forget about everything (possibly storing smart pointers, eg std::unique_ptr<T>
).
If you really want to go the hard way you could setup things like these:
i
)i == LENGTH_OF_ARRAY - 1
do nothing, otherwise swap element at i
and at LENGTH_OF_ARRAY - 1
so that the element to be removed is in last positiondelete array[LENGTH_OF_ARRAY - 1]
to destroy last elementarray = realloc(array, (LENGTH_OF_ARRAY - 1) * sizeof(array[0]))
to release memory in the array for removed element, and update LENGTH_OF_ARRAY
Upvotes: 1