[在第一阶段,我创建了一个具有一些属性的对象Planet,例如name
,type
和distanceToEarth
。然后,我创建了一个存储库,基本上是一个由动态数组元素及其长度和最大容量组成的结构。
typedef enum {
NEPTUNE_LIKE,
GAS_GIANT,
TERRESTRIAL,
SUPER_EARTH,
UNKNOWN
}PlanetType;
typedef struct {
char name[30];
PlanetType type;
float distanceToEarth;
}Planet;
Planet createPlanet(char name[], PlanetType type, double distance) {
Planet pl;
strcpy(pl.name, name);
pl.distanceToEarth = distance;
pl.type = type;
return pl;
}
typedef struct
{
Planet* elems; /** dynamic array containing the planets */
int length; /** actual length of the array */
int capacity; /** maximum capacity of the array */
} PlanetRepo;
PlanetRepo createPlanetRepo(int capacity) {
/// create a new planet repo; the elems field must be dynamically allocated (malloc)
PlanetRepo r;
r.capacity = capacity;
r.length = 0;
r.elems = (Planet*) malloc(sizeof(Planet)*capacity);
return r;
}
bool remove(PlanetRepo* repo, Planet pl) {
/// @todo remove planet pl from the repository
/// return false if the planet does not exist in the repository
return false;
}
我的问题与remove()函数有关。我不知道应该如何从动态分配的数组中删除该对象。
当然,这不是完整的代码,但是我只选择了相关部分。如果我忘了包含某些内容,请告诉我。
由于您坚持要标记C ++,而不是C:
在C ++中,您根本不会定义PlanetRepo
和关联的函数。相反,您只需声明一个类型为
std::vector<Planet>
或可能取决于用例(但不太可能)
std::list<Planet>
这两个都已经具有从其中删除元素的成员函数.erase
。>>
在C ++中,您也不会写
typedef struct { char name[30]; PlanetType type; float distanceToEarth; }Planet;
但是代替
struct Planet { char name[30]; PlanetType type; float distanceToEarth; };
并且您很可能使用
std::string
代替char[30]
作为name
的类型。
代替函数Planet createPlanet(char name[], PlanetType type, double distance)
,您将为Planet
定义一个构造函数:
struct Planet { std::string name; PlanetType type; float distanceToEarth; Planet(std::string name, PlanetType type, double distance) : name(name), type(type), distance(distance) {} };
并且可能使成员成为
private
。
您也不会定义一个无范围的枚举,而是一个有范围的枚举(自C ++ 11起,请参见Why is enum class preferred over plain enum?。
由于这是C而不是C ++程序,因此可以使用链接列表,使您可以删除动态分配的“数组”中的元素。
就像C ++实现数据结构之前提到的那样,因此您可以轻松地存储行星。但是您可以执行以下操作: