将结构分配给另一个结构会导致垃圾

Assigning a structure to another structure results in garbage

我代码中使用的两种结构,一种是嵌套

struct Class
{
    std::string name;
    int units;
    char grade;
};
struct Student
{
    std::string name;
    int id;
    int num;
    double gpa;
    Class classes[20];
};

我正在尝试找出一种方法来按照 ID 的升序对 all_students[100] 数组中的结构进行排序。我的想法是,从位置 1 开始计数,然后将其与前一个元素进行比较。如果它小于前一个元素,那么我将有一个 Student 类型的临时数组来等同于它,那么在 all_students 数组中切换它们的位置将是一件简单的事情。但是,当我打印结果时,其中一个元素最终变成了垃圾数字,而且顺序不对。这是针对大学中级 C++ class 的,我们不允许使用指针或向量,因为他还没有教我们这些。有什么不清楚的随时问我。

根据ID排序结构的函数

void sort_id(Student all_students[100], const int SIZE)
{
Student temporary[1];
int counter = 1;
while (counter < SIZE + 1)
{
    if (all_students[counter].id < all_students[counter - 1].id)
    {
        temporary[0] = all_students[counter];
        all_students[counter] = all_students[counter - 1];
        all_students[counter - 1] = temporary[0];
        counter = 1;
    }
    counter++;
}
display(all_students, SIZE);
}

您的学生数组范围为 0、99。允许计数器从 1 到 100。

我假设 SIZE 为 100(在这种情况下,您可能应该让数组计数也为 SIZE 而不是硬编码为 100,如果这不仅仅是为我们键入示例的产物) .

您可以用任何一种方式执行 while 循环

while(counter < SIZE)

并从 0 开始计数器,或者

while (counter < SIZE+1)

并从 1 开始计数,但如果执行后者,则需要从数组下标中减去 1。我相信这就是标准(根据我的观察)从 0 开始的原因。

编辑:我不是反对者!另外,只是另一个快速评论,真的没有理由让你的临时数组成为一个数组。只要

Student temporary;

我忽略了一个事实,即我允许循环访问的元素多于数组实际保存的元素。这就是我得到垃圾的原因,因为循环正在访问不存在的数据。

我通过更改 while (counter < SIZE + 1) 解决了这个问题 至:while (counter < SIZE )

然后为了解决第二个关于排序的问题,我需要确保循环在切换后从头开始,以防需要再次切换到较低的元素。所以我在counter = 1

之后写了continue;

您的代码有一些问题:

  1. 您不需要创建大小为 1 的数组来用作临时变量。
  2. 您的计数器的范围是 1 到 100,您将越界:大小为 100 的数组的索引范围是 0 到 99。

以下解决方案使用 insertion sort 对学生数组进行排序,它为您的排序算法提供了一种更快的替代方法。请注意,插入排序仅适用于足够小或接近排序的数组。

void sort_id(Student* all_students, int size)
{
    Student temporary;
    int i = 1;
    while(i < size) // Read my note below.
    {
        temporary = all_students[i];
        int j = i - 1;
        while(j >= 0 && temporary.id < all_students[j].id)
        {
            all_students[j+1] = all_students[j]
            j--;
        }
        all_students[j+1] = temporary;
        i++;
    }
    display(all_students, size);
}

注意: 外层的 while 循环也可以用这样的 for 循环完成:

for(int i = 1; i < size; i++)
{
    // rest of the code ...
}

通常,当您事先知道将完成多少次迭代时,会使用 for 循环。在这种情况下,我们知道外循环将从 0 迭代到 size - 1。内循环是一个while循环,因为我们不知道它什么时候会停止。