在c ++中从数组中删除对象

时间:2015-11-21 19:41:51

标签: c++ arrays object

水果类:

#include <string>
using namespace std;

class Fruits {
    string color;
public:
    Fruits() {
        color = "r";
    }
};

主:

#include "Fruits.cpp"

void main() {
    Fruits* fruits[6];
    fruits[0] = new Fruits();
//  delete[] fruits[0];  // <-- does not work (deletes one object)
//  delete[] fruits; //     <-- does not work (deletes all objects in the array)
}

我该怎么做?

3 个答案:

答案 0 :(得分:1)

delete fruits[0]将为您删除该对象。 delete[]用于删除该数组的所有非null元素,但fruits[0]不是对象数组。

答案 1 :(得分:1)

您无法使用标准C ++数组删除数组项。请改用std::vector

new[]初始化的数组是指针指向其第一个存储单元的缓冲区。在向量和列表中,元素是链接的。因此,每个元素都指向其上一个和下一个项目,从而可以轻松删除或插入项目。为此,它需要更多的内存。

示例

// constructing vectors
#include <iostream>
#include <vector>

int main ()
{
  // constructors used in the same order as described above:
  std::vector<int> first;                                // empty vector of ints
  std::vector<int> second (4,100);                       // four ints with value 100
  std::vector<int> third (second.begin(),second.end());  // iterating through second
  std::vector<int> fourth (third);                       // a copy of third

  // the iterator constructor can also be used to construct from arrays:
  int myints[] = {16,2,77,29};
  std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

  std::cout << "The contents of fifth are:";
  for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

只是为了澄清,

delete fruits[0]

将删除位于数组第0个元素的水果,但不会将其从数组中删除或使数组中的元素更短。

答案 2 :(得分:0)

你不能delete未使用new分配的内容,也不能混合new []deletenewdelete []

首先,您需要为元素动态分配空间,而不一定是指针数组。删除一个元素可以通过移动所有后面的元素来完成,所以下一个元素取代了被移除的元素,在数组的末尾留下一个未使用的元素,然后可能缩小分配的空间。

这实际上是使用std::vector实现的,您不应该自己作为初学者实现它。如果您正在寻求此功能,请使用std::vector