用动态内存管理创建类列表数组

Creating List Like Array with Dynamic Memory Management

本文关键字:列表 数组 创建 管理 动态 内存      更新时间:2023-10-16

有讲座班和学生班。我们正在尝试用数组保存课堂上的学生信息。

例如:

Student * studentList = new Student[numberOfStudent];
studentAdd("Mary");
studentDelete("Mary");

问题:用户没有给出学生人数,当用户添加一个新的学生时,学生人数正在增加。所以我认为我需要一个像结构器一样的列表来保存它们,但这是禁止的。你有什么比我的临时解决办法更有效的办法吗?

我的临时解决方案:保存学生人数和数组大小,当学生人数大于数组大小时,将数组复制到一个比旧数组大的新数组。

这个问题与我的作业有关,我们通过

*使用指针动态分配内存

*不使用任何固定大小的静态数组或其他数据结构,如来自标准库的向量

如果不想使用对象,可以直接使用函数。注意,我没有编译这段代码。

#include <iostream>
#include <sstream>
#include <string>
#include "Student.h"
void add(Student **list, Student *rhs);
void destroy(Student **list,int const &idx);
void destroy(Student **list,const char* student_name); //find the student name and delete
void resize(Student **list,int const &idx);
Student** begin(Student **list,); //get the first Student
Student** end(Student **list,); //the end of the array
void clear(Student **list,); //drop all Students
int main(int argc, char **argv)
{
  if(argc < 2)
  {
    stc::cerr << "not enough parameters" << std::endl;
  } 
  istringstream buffer(argv[1]);
  int value;
  buffer >> value; 
  Student ** studentList = new *Student[value];
  int s
  add(studentList, "Mary");
  destroy(studentList, "Mary");
  return(0);
}
void add(Student **list, Student *rhs) { /*definition*/ }
void destroy(Student **list, int const &idx) { /*definition*/ }
void destroy(Student **list, const char* student_name) { /*definition*/ }
void resize(Student **list, int const &idx) { /*definition*/ }
Student** begin(Student **list) { /*definition*/ }
Student** end(Student **list) { /*definition*/ }
void clear(Student **list) { /*definition*/ }

现在把这些都定义好,就完成了

我不推荐这种方法

我将使用对象…并考虑到PaulMcKenzie所说的容量

class StudentList
{
private:
  Student **list;
  std::size_t size;
  std::size_t capacity;
public:
  StudentList(){}
  ~StudentList(){ this->clear(); }
  inline void add(Student *rhs) { //definition }
  inline void destroy(int const &idx) { //definition }
  inline void destroy(const char* student_name) { //definition }
  inline void resize(int const &idx) { //definition }
  inline Student** begin() { //definition }
  inline Student** end() { //definition }
  inline void clear() { //definition }
};

如果可能的话

迭代器

在vector下面你会发现一个类似的实现,它使用Iterators来封装Student**