无法为结构重载 = 运算符。程序可以编译,但在执行直接合并时会崩溃。
结构:
struct Student
{
QString fio;
int group;
int ysp[5];
Student& operator = (const Student &s)
{
fio = s.fio;
group = s.group;
ysp[0] = s.ysp[0];
ysp[1] = s.ysp[1];
ysp[2] = s.ysp[2];
ysp[3] = s.ysp[3];
ysp[4] = s.ysp[4];
ysp[5] = s.ysp[5];
return (*this);
}
};
直接归并排序:
void MainWindow::Merge(Student *list_S, int left, int right)
{
if (right == left) return;
if (right - left == 1)
{
if (ui->Ascending->isChecked())
{
if (list_S[right].group < list_S[left].group) swap(list_S[right], list_S[left]);
}
if (ui->Descending->isChecked())
{
if (list_S[right].group > list_S[left].group) swap(list_S[right], list_S[left]);
}
return;
}
int m = (right + left) / 2;
Merge(list_S,left, m);
Merge(list_S,m + 1, right);
Student buf[right];
int xl = left;
int xr = m + 1;
int cur = 0;
while (right - left + 1 != cur)
{
if (xl > m) buf[cur++] = list_S[xr++];
else if (xr > right) buf[cur++] = list_S[xl++];
else if (ui->Ascending->isChecked() && list_S[xl].group > list_S[xr].group)buf[cur++] = list_S[xr++];
else if (ui->Descending->isChecked() && list_S[xl].group < list_S[xr].group)buf[cur++] = list_S[xr++];
else buf[cur++] = list_S[xl++];
}
for (int i = 0; i < cur; i++) list_S[i + left] = buf[i];
}
如果在排序中更正,一切都会正常工作:
Student buf[right+1];
线
多余。数组中有 5 个元素,这里有 5 个并复制(从 0 到 4),在这一行中,您正在向内存中添加内容。
但实际上,在这种情况下没有必要定义赋值运算符,因为默认的赋值运算符(由编译器自动合成)的作用完全相同。