C++ c++;链表创建链表的链表
此行中的代码发送错误 课程[“CS”]。学生=新课程*[1] 我想创建课程的链接列表包含学生的链接列表 这是密码C++ c++;链表创建链表的链表,c++,linked-list,C++,Linked List,此行中的代码发送错误 课程[“CS”]。学生=新课程*[1] 我想创建课程的链接列表包含学生的链接列表 这是密码 struct Student{ string name; int id; int grade; Student(string n, int i, int gd ){ name=n; id=i; grade=gd; } }; struct Course{ string C_Name; St
struct Student{
string name;
int id;
int grade;
Student(string n, int i, int gd ){
name=n;
id=i;
grade=gd;
}
};
struct Course{
string C_Name;
Student **student;
int index;
void add_student(Student *new_student){
student[++index]=new_student;
}
};
Course course[4];
void init(){
course["CS"].student=new Course*[1];
}
在C++中,你没有定义课程[String ],所以你可能不使用“CS”作为课程类型对象的索引。 而*.student是类学生的对象,而不是课程类型
#include <iostream>
#include <stdexcept>
using namespace std;
struct Student{
string name;
int id;
int grade;
Student(string n, int i, int gd ){
name=n;
id=i;
grade=gd;
}
};
struct Course{
string C_Name;
Student **student;
int index;
void add_student(Student *new_student){
student[++index]=new_student;
}
};
Course course[4];
void init(){
// Need allocate space for a new object of class "Course"
Course course;
course.student = new Student*[1];// "student" is Student type but not Course
}
int main()
{
try{
init();
}
catch(...){
return -1;
}
std::cerr <<"your debug info" <<endl;
return 0;
}
#包括
#包括
使用名称空间std;
结构学生{
字符串名;
int-id;
国际等级;
学生(字符串n,整数i,整数gd){
name=n;
id=i;
等级=gd;
}
};
结构课程{
字符串C_名称;
学生**学生;
整数指数;
无效添加学生(学生*新学生){
学生[++索引]=新学生;
}
};
课程[4];
void init(){
//需要为“课程”类的新对象分配空间
课程;
course.student=新学生*[1];/“student”是学生类型,但不是课程
}
int main()
{
试一试{
init();
}
捕获(…){
返回-1;
}
您的代码不包含任何类型的链表,只包含普通数组。
除此之外,最后一行(course[“CS”].student=new course*[1];
)包含一些无效语法
- 必须使用整型或枚举类型来访问数组(
string
s或char[]
不起作用)
- 不允许将
课程**
分配给学生**
对象
链接列表包含每个节点都有指向下一个节点的指针的节点。最后一个节点通常有一个值为nullptr
(C++11)或0
(旧标准)的指针。注意:还有一个所谓的双链接列表,其中每个节点还存储指向前一个节点的指针。
节点包含您希望它存储的所有数据。
例如:
要创建链表,首先从一个节点开始并设置next=nullptr;//0
。要添加另一个节点,只需创建一个新节点并更改第一个节点的指针。
例如:
您开始看到一个模式。要在前面插入,只需创建一个新的节点
,并将其下一个
设置为第一个已存在的节点。要在两个节点之间插入,请说节点1
和节点2
:
node1 -> next = newNode;
newNode -> next = node2;
为了使它更美观,我们通常编写一个包含函数的包装器类,例如
InsertNodeAt(Node* node, uint index);
Node* GetNodeAt(uint index);
RemoveNodeAt(uint index);
由于您有两种不同类型的对象(Student
和Curse
),因此您可能希望使用模板并避免为每种类型编写链表类
如果你想自己创建链接列表,我建议你做一些额外的研究(谷歌是你的朋友),因为我只提到了几件事
如果您不介意使用C++标准库,您可能会对已经使用的链表类使用<代码> STD::转发列表(标准链表)和<代码> STD::列表(双链表)。
不是数组的有效索引。使用std::map/std::unordered\u map如果您想使用stringsalso进行索引,student
是student
指针,因此分配课程*
将不起作用。如果用户正在谈论创建链接列表,我将假定std::map是不允许的,尽管问题应该更新要提到需求,你根本不应该使用数组。你应该做的是在你开始写任何代码之前,再学习链接列表。看起来你需要复习一下关于数组的章节。你能告诉我插入函数是什么吗?你可以在C++或OOP书籍中得到插入函数的格式。看着它。我会做这件事的。这很简单,但保持联系我需要你。我不打算为你写代码。我想如果你自己做的话,你会学得更好。:)不管怎样,如果你只想为你的项目使用代码,谷歌吧。很多人已经做了示例实现。小姐,我说如果我面对障碍,我不会再问你了:)那就尽管问吧。:)
node1 -> next = newNode;
newNode -> next = node2;
InsertNodeAt(Node* node, uint index);
Node* GetNodeAt(uint index);
RemoveNodeAt(uint index);