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

时间:2015-10-28 21:10:26

标签: c++ arrays pointers dynamic

我正在进行一项任务,我们必须创建一个“学生”对象,其中“课程”成员数组是动态的,因此用户可以从一个课程进入数组中他们想要的数量。我一直在尝试这种方式,只是无法让数组调整大小并接受新元素。这是我现在的代码:

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数组。即如果course =“one”,dynArray [0] =“o”,dynArray [1] =“n”等等。有谁知道如何防止这种情况发生?

screenshot

2 个答案:

答案 0 :(得分:1)

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

dynArray[numCourses] = course;

在检查numCurses > numC之前,这意味着dynArray[numCourses]访问内存越界(边界为0numC - 1

令我感到有趣的另一件事是addElement方法将numCourses作为参数。我希望它的行为应该与std::vector<T>::push_back类似。你确定这个论点是必要的吗?

我想评论的最后一件事是不复制dynArray的值。请查看std::copy_n如何进行复制。

答案 1 :(得分:0)

我不确定这是否会被视为作弊,但这是对如何实施std :: vector的分解。您可以将其用作参考,然后选择您需要的部件。

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