问题
Fruits class:
#include <string>
using namespace std;
class Fruits {
string color;
public:
Fruits() {
color = "r";
}
};
Main:
#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)
}
How can I do this?
回答1:
delete fruits[0]
will delete that one object for you. delete[]
instead serves to delete all non-null elements of that array, but fruits[0]
is not an array of objects.
回答2:
You can't remove an item of an array using standard C++ arrays. Use std::vector
instead.
An array like initialized with new[]
is a buffer which pointer points at its first memory cell. In vectors and lists, elements are linked. Each element therefore points at its previous and next item, making it easy to remove or insert items. For this purpose, it requires more memory, though.
Example
// 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;
}
And just for clarification,
delete fruits[0]
will delete the fruit that is located at the 0th element of the array, but it will not remove it from the array or make the array one element shorter.
回答3:
You cannot delete
what wasn't allocated with new
and you can't mix new []
and delete
nor new
and delete []
.
Firstly, you need dynamically allocated space for the elements, no necessarily array of pointers. Removal of an element can be done by shifting all the following elements, so the next element takes the place of the removed element, leaving an unused element at the end of the array, then possibly shrinking the allocated space.
This is practically implemented with std::vector
and you shouldn't be implementing it yourself as a beginner. If you're seeking this functionality, use std::vector
!
来源:https://stackoverflow.com/questions/33847783/delete-object-from-array-in-c