c ++链表创建链表的链表

时间:2015-05-04 15:08:18

标签: 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; 
    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];
}

2 个答案:

答案 0 :(得分:0)

在c ++中你没有定义课程[" string"],所以你不能使用" CS"作为Course类型对象的索引 和* .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;
}

而且在我看来,在c ++中你可以尝试参考,并且它可以在班级课程的定义中反驳班级学生。以这种方式使用打印机可能会导致意外错误。

答案 1 :(得分:0)

您的代码不包含任何类型的链接列表,只包含普通数组。 除此之外,最后一行(course["CS"].student=new Course*[1];)包含一些无效的语法。

  • 必须使用整数或枚举类型来访问数组(stringchar[]无效)
  • 不允许将Course**分配给Student**对象

链表包含节点,每个节点都有一个指向下一个节点的指针。最后一个节点通常有一个值为nullptr(C ++ 11)或0(旧标准)的指针。注意:还有一个所谓的双链表,其中每个节点还存储指向前一个节点的指针。 节点包含您希望它存储的所有数据。 例如:

struct Node {
    Node* next;
    // other node data here
};

要创建链接列表,首先要从一个节点开始并设置next = nullptr; // 0。要添加另一个节点,只需创建一个新节点并更改第一个节点的指针。 例如:

Node* node1 = new Node();
node1 -> next = nullptr;

Node* node2 = new Node();
node2 -> next = nullptr;

node1 -> next = node2;

你开始看到一种模式。要在前面插入,只需创建一个新的Node并将其next设置为第一个已存在的节点。要在两个节点之间插入,请说node1node2

node1 -> next = newNode;
newNode -> next = node2;

为了使它更好,通常会编写一个包含

等函数的包装类
InsertNodeAt(Node* node, uint index);
Node* GetNodeAt(uint index);
RemoveNodeAt(uint index);

由于您有两种不同类型的对象(StudentCurse),您可能希望使用模板并避免为每种类型编写链接列表类。

如果您想自己创建链接列表,我建议您做一些额外的研究(谷歌是您的朋友),因为我只提到了一些事情。

如果您不介意使用c ++标准库,您可能会对使用已预先制作的链表类std::forward_list(标准链表)和std::list(双链表)感兴趣。