【问题标题】:pushing a vector of structures into a structure?将结构向量推入结构?
【发布时间】:2019-03-06 17:05:07
【问题描述】:

我需要创建一个结构 student 来嵌套另一个名为 course 的结构。然后在结构“课程”中填写学生注册的人数以及他们的 ID 和姓名

我不确定如何将结构“课程”属性推回已经将结构课程作为向量的结构学生中

    #include <iostream>
    #include <string>
    #include<vector>
    using namespace std;

    struct course{

        int ID;
        string name;

    };
    struct student{
        int ID;
        string name;
        vector <course> ofcourses;


    };

    void studentDeclare(student &B1){

        int coursecount;
        cout <<" Student ID: " <<endl;
        cin>>B1.ID;
        cout <<" Student name: " <<endl;
        cin>>B1.name;
        cout <<" How many courses?: " <<endl;
        cin >> coursecount;

        int TempID;
        string TempName;
        for(int i = 0; i<coursecount;i++)
        {
            cout <<" Enter course ID: " <<endl;
            cin >> TempID;
            B1.ofcourses.ID.push_back[TempID];
            cout <<" Enter course name: " <<endl;
            string TempName;
            cin>>TempName;
            B1.ofcourses.name.push_back[TempName];
        }

    };

    int main()
{
    student boy;
    studentDeclare(boy);
    print(boy);

    system("pause");
}

【问题讨论】:

    标签: c++ function vector structure


    【解决方案1】:
    B1.ofcourses.ID.push_back[TempID];
    B1.ofcourses.name.push_back[TempName];
    

    不对。

    B1.ofcourses 是 std::vector&lt;course&gt;。它没有名为ID 或name 的成员。

    您需要构造一个course 对象并将其推送到B1.ofourses。

    for(int i = 0; i<coursecount;i++)
    {
        course c;
        cout <<" Enter course ID: " <<endl;
        cin >> c.ID;
        cout <<" Enter course name: " <<endl;
        cin >> c.name;
    
        B1.ofcourses.push_back(c);
    }
    

    【讨论】:

    • 澄清了很多,所以我可以通过这种方式访问​​它们:B1.ofcourses.name.push_back[TempName]; ,,,,,,但必须按成员将它们复制到其中吗?
    • @user10798572,我没关注你问是否可以使用B1.ofcourses.name.push_back[TempName];访问std::vector中的对象?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    相关资源
    最近更新 更多