简体   繁体   English

删除数组中的元素,C ++

[英]removing elements in an array, c++

I have an array of sockets (pfd[nfd].fd). 我有一个套接字数组(pfd [nfd] .fd)。 I also have an array of pointers (event_tracking* track[10]). 我还有一个指针数组(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? 我知道您可以调用delete运算符来调用跟踪的析构函数,但是由于现在缺少一个元素,我不确定如何重新排列数组中的元素? Or how to delete and reorder the pfd array? 或者如何删除并重新排序pfd数组?

Any help would be appreciated! 任何帮助,将不胜感激! I can't find any examples of deleting and reordering arrays in my text. 我找不到在文本中删除和重新排序数组的任何示例。

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> ). C ++解决方案应使用std::vectorstd::array并忽略所有内容(可能存储智能指针,例如std::unique_ptr<T> )。

If you really want to go the hard way you could setup things like these: 如果您确实想采用艰辛的方法,则可以设置以下内容:

  • find element to remove (index i ) 查找要删除的元素(索引i
  • if 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 position 如果i == LENGTH_OF_ARRAY - 1不执行任何操作,否则在iLENGTH_OF_ARRAY - 1处交换元素,以便要删除的元素位于最后位置
  • call delete array[LENGTH_OF_ARRAY - 1] to destroy last element 调用delete array[LENGTH_OF_ARRAY - 1]销毁最后一个元素
  • call array = realloc(array, (LENGTH_OF_ARRAY - 1) * sizeof(array[0])) to release memory in the array for removed element, and update LENGTH_OF_ARRAY 调用array = realloc(array, (LENGTH_OF_ARRAY - 1) * sizeof(array[0]))以释放数组中要删除的元素的内存,并更新LENGTH_OF_ARRAY

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 . 使用new[]分配的数组,您将不会重新分配任何内容,但是可以调整vector大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM