不使用矢量的动态字符串数组

Dynamic string array without using vector

本文关键字:动态 字符串 数组      更新时间:2023-10-16

我正在做一项作业,我们必须创建一个"student"对象,该对象具有动态的"course"成员数组,这样用户就可以在数组中从一门课程输入任意多门课程。我一直在尝试各种方法,但无法调整数组的大小并接受新元素。这是我现在的代码:

cout << "Enter student name > ";
cin >> name;
Student firstStudent(name);
cout << endl << "Enter "done" when you are complete";
cout << endl << "Enter a new course : ";
cin >> course;
while (course != "done") {
    numCourses++;
    firstStudent.addElement(numCourses, course);//makes the array bigger
    cout << endl << "Enter a new course : ";
    cin >> course;
}//end while

成员变量和构造函数:

class Student
{
private:
   string name;//name of student
   string *dynArray = new string[1];//array
public:
Student::Student(string name)
{
   this->name = name;
   this->numC = 1;//initialized to one to start with    
}

调整大小并向数组添加元素:

void Student::addElement(int numCourses, string &course) {//DYNAMIC ARRAY
    if (numCourses > this->numC) {//checks if there are more courses than there is room in the array
       this->numC = numCourses; //this changes the member variable amount
       dynArray[numCourses] = course;//adds new course to array
       string *temp = new string[numC];//create bigger temp array
       temp = dynArray;//write original to temp
       delete[]dynArray; //this tells it that it's an array
       dynArray = temp;//make dynarray point to temp
    }
    else {
       dynArray[numCourses] = course;//adds new course to array
    }
}//end addElement

即使我设法消除了编译错误,它也经常会出现运行时错误。我确信这与指针/复制数组有关,但我只是在学习,还没有掌握这些概念。

编辑:dynArray[numCourses]=课程;创建一个char数组。ie if course="one",dynArray[0]="o",dynArray[1]="n"等。有人知道如何防止这种情况发生吗?

屏幕截图

第一行看起来不太正确的是:

dynArray[numCourses] = course;

在检查numCurses > numC之前,这意味着dynArray[numCourses]访问内存超出了界限(界限是0numC - 1

另一件令我感兴趣的事情是,addElement方法将numCourses作为自变量。我希望它的行为与std::vector<T>::push_back类似。你确定这个论点是必要的吗?

我最不想评论的是dynArray中的值没有被复制。请看一下std::copy_n中关于如何进行复制的内容。

我不确定这是否会被视为作弊,但以下是std::vector的实现方式。你可以把它作为参考,然后挑选出你需要的零件。

http://codefreakr.com/how-is-c-stl-implemented-internally/