//排序职工
void WorkerManager::Sort_Emp()
{
if (this->m_FileIsEmpty)
{
cout << "文件不存在或记录为空" << endl;
system("pause");
system("cls");
}
else
{
cout << "请选择排序方式:" << endl;
cout << "1.按照工号进行升序" << endl;
cout << "2.按照工号进行降序" << endl;
int select = 0;
cin >> select;
for (int i = 0; i < m_EmpNum; i++)
{
int minOrMax = i;//声明最小值下标
for (int j = i + 1; i < this->m_EmpNum; j++)
{
//升序
if (select == 1)
{
if (this->m_EmpArray[minOrMax]->m_ID > this->m_EmpArray[j]->m_ID)
{
minOrMax = j;
}
}
//降序
else
{
if (m_EmpArray[minOrMax]->m_ID < m_EmpArray[j]->m_ID)
{
minOrMax = j;
}
}
}
//判断一开始认定 最小值或最大值 是不是计算的最大值或最小值,如果不是,交互数据
if (i != minOrMax)
{
Worker* temp = m_EmpArray[i];
m_EmpArray[i] = m_EmpArray[minOrMax];
m_EmpArray[minOrMax] = temp;
}
}
cout << "排序成功,排序后的结果为:" << endl;
this->save();//排序后结果保存到文件中
this->Show_Emp();//展示所有
}
}
老是报错说是运行在升序处发生访问冲突。
我把两段升序和降序代码分开各自写,还是不行
第3行这句:for (int i = 0; i < m_EmpNum; i++) 修改, i < m_EmpNum; 后面的循环是 for(j = i + 1;....) 会造成数组越界操作。第7行for(.....i < this->m_EmpNum; j++)中间 i < this->m_EmpNum; 这里应该是:j < this->m_EmpNum; ,修改如下,供参考:
void WorkerManager::Sort_Emp()
{
if (this->m_FileIsEmpty)
{
cout << "文件不存在或记录为空" << endl;
system("pause");
system("cls");
}
else{
cout << "请选择排序方式:" << endl;
cout << "1.按照工号进行升序" << endl;
cout << "2.按照工号进行降序" << endl;
int select = 0;
cin >> select;
for (int i = 0; i < this->m_EmpNum - 1; i++) //修改
//for (int i = 0; i < m_EmpNum; i++)
{
int minOrMax = i;//声明最小值下标
for (int j = i + 1; j < this->m_EmpNum; j++) //修改
//for (int j = i + 1; i < this->m_EmpNum; j++)
{
if (select == 1) //升序
{
if (this->m_EmpArray[minOrMax]->m_ID > this->m_EmpArray[j]->m_ID)
{
minOrMax = j;
}
}
else //降序
{
if (this->m_EmpArray[minOrMax]->m_ID < this->m_EmpArray[j]->m_ID)
{
minOrMax = j;
}
}
}
//判断一开始认定 最小值或最大值 是不是计算的最大值或最小值,如果不是,交互数据
if (i != minOrMax)
{
Worker* temp = m_EmpArray[i];
m_EmpArray[i] = m_EmpArray[minOrMax];
m_EmpArray[minOrMax] = temp;
}
}
cout << "排序成功,排序后的结果为:" << endl;
this->save();//排序后结果保存到文件中
this->Show_Emp();//展示所有
}
}
越界?野指针?