不使用矢量的动态字符串数组
Dynamic string array without using vector
我正在做一项作业,我们必须创建一个"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]
访问内存超出了界限(界限是0
到numC - 1
。
另一件令我感兴趣的事情是,addElement
方法将numCourses
作为自变量。我希望它的行为与std::vector<T>::push_back
类似。你确定这个论点是必要的吗?
我最不想评论的是dynArray
中的值没有被复制。请看一下std::copy_n
中关于如何进行复制的内容。
我不确定这是否会被视为作弊,但以下是std::vector的实现方式。你可以把它作为参考,然后挑选出你需要的零件。
http://codefreakr.com/how-is-c-stl-implemented-internally/
相关文章:
- 分段故障 11,从类函数显示动态 C 字符串
- 删除动态字符串时程序崩溃
- C++动态字符串的动态数组
- 当有1个以上的对象时,动态字符串类断裂与SEG故障
- 动态字符串阵列构造函数和空返回
- 动态 c 字符串类的重载>>运算符
- 调整动态字符串的大小会导致内存泄漏
- Objective-C 预处理器定义,动态 C 字符串到 NSString 声明
- 连接两个动态字符串数组
- 动态字符串网格C++生成器
- 当我重载动态字符串类的运算符时没有匹配的构造函数
- 动态字符串数组分配错误
- 如何在VS调试器中查看c++中动态字符串数组的内容
- c++动态字符串数组分配
- 不使用矢量的动态字符串数组
- 动态字符串数组容器类在delete[]时挂起
- 初始化动态字符串数组(c++)
- 创建动态字符串数组时出现Seg错误
- 无法从函数返回动态字符串
- 如何使动态字符串在控制台中使用UTF-8 ?