C++结构题

标签 c++ struct

我用谷歌搜索了与结构相关的内容,我能够看到它们是如何使用的;但是,我无法清楚地找出其中的一些。

假设我有 2 个结构

struct Student {
    int age;
    int height;
};

struct School {
    Student information;
};

假设我想根据输入文件处理信息 School[i].Student[j].age 或 height。

int main() {
    int school_number = 20;
    int student_number = 50;

    School school[school_number-1]; // is this the correct way to create it? since [0] is the first school

    for (int i=0; i < school_number; i++) {
        for (int j=0; j < student_number; j++) {
            getline(file, line); // let's say the line has student's age and height.
            istringstream c(line); 
            c >> school[i].information[j].age >> school[i].information[j].height;
        }
    }
}

我认为这可以完成工作,但我没有匹配到“operator[]”(操作数类型是“Student”和“int”)编译错误。

我错过了什么?

还是学生的时候

Student info[student_number-1];

for (int i=0; i < student_number; i++) {
        getline(file, line);
        istringstream c(line);
        c >> information[i].age >> information[i].height;
}

这个工作没有问题,但我仍然不确定我需要为 2 个结构做些什么,其中一个调用另一个。

还有一个问题,

当我在寻找的时候,我看到了很多

School *id = new School[school_number-1];

是这样的。这与

有何不同
School school[school_number-1];

这个?

我看到一个指针,所以我很确定它做了一些事情,但根据它们的使用方式,它们看起来几乎相同。

编辑:我尝试了一点点,但仍然不确定在这种情况下如何使用 vector 。

对于上述情况,

int main() {
    vector[Student] student;

    int school_number = 20;
    int student_number = 50;

    School school[school_number-1]; // is this the correct way to create it? since [0] is the first school

    for (int i=0; i < school_number; i++) {
        for (int j=0; j < student_number; j++) {
            getline(file, line); // let's say the line has student's age and height.
            istringstream c(line); 
            c >> school[i].information[j].age >> school[i].information[j].height;
        }
    }
}

如果我打电话

vector[Student] student;

如何修改行

c >> school[i].information[j].age >> school[i].information[j].height;

使用我刚刚创建的变量 student?

最佳答案

如果你想声明一个数组,它必须有一个常量大小。你可能想要的是 std::vector<Student>

关于C++结构题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064722/

相关文章:

c++ - 将记录数组的元素传递给临时记录数组的问题

c++ - 替换模板上的虚函数

c++ - 链表中的运算符重载 <<

c++ - 多线程环境中的 Linux 高分辨率计时器?

c - 如何在结构体中初始化 int 指针并将其分配给 C 中的数组?

c++ - 将带有指针数组的结构保存到文件中

c - 将两个大数相加

c++ - 编译静态库时收集所有头文件

c++ - 如何从 STL 容器中按子字符串删除元素

c - 结构指针中需要一些说明