【发布时间】:2012-10-30 20:56:52
【问题描述】:
大家好,我正在尝试完成一项课程作业,我需要按员工的 ID 号对包含员工的文件进行排序。文件中有 10 行,每行都有一个员工信息。顺序是 ID LASTNAME FIRSTNAME
在我编写排序函数并将所有数据正确复制到数组中之前,程序运行良好,但现在在添加排序函数后,我不断收到访问冲突,没有提示是什么原因造成的。
我将不胜感激。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Employee
{
public:
int _id;
string _lastName;
string _firstName;
Employee()
{
_id = 0;
_lastName = "n/a";
_firstName = "n/a";
}
};
void copyFile10(Employee [], int);
void sortFile10(Employee [], int);
int main()
{
const int size10 = 10;
Employee employees10[size10];
copyFile10(employees10, size10); //1.fill array/copy file
sortFile10(employees10, size10); //2. sort
system("pause");
return 0;
}
void copyFile10(Employee employees10[], const int size)
{
ifstream data10("data_10.dat");
for(int count = 0; count < 10; count++) //1.fill array/copy file
{
data10 >> employees10[count]._id;
data10 >> employees10[count]._lastName;
data10 >> employees10[count]._firstName;
}
data10.close();
}
void sortFile10(Employee employees10[], const int size)
{
Employee buff1;
Employee buff2;
int counter = 0;
bool ordered = false;
while (ordered == false)
{
for(int count = 0; count < size-1; count++)
{
if(employees10[count]._id > employees10[count+1]._id)
{
buff1._id = employees10[count+1]._id;
buff1._lastName = employees10[count+1]._lastName;
buff1._firstName = employees10[count+1]._firstName;
buff2._id = employees10[count]._id;
buff2._lastName = employees10[count]._lastName;
buff2._firstName = employees10[count]._firstName;
employees10[count]._id = buff1._id;
employees10[count]._lastName = buff1._lastName;
employees10[count]._firstName = buff1._firstName;
employees10[count+1]._id = buff2._id;
employees10[count+1]._lastName = buff2._lastName;
employees10[count+1]._lastName = buff2._lastName;
counter++;
}
if(counter == 0)
ordered = true;
else
counter = 0;
}
}
}
【问题讨论】:
-
当您的程序在调试器下崩溃时,您确定有可用的调用堆栈吗?
-
在这条线上崩溃了吗? if(employees10[count]._id > employees10[count+1]._id); 'count+1' 为 10,但最大数组索引为 9。
-
这可能是马克史蒂文斯,但它没有告诉我它是什么线。我会尝试找到一个解决方案,看看是否能解决它。
-
@sircrisp 这是冒泡排序和编程 101 的常见错误。您将“this”条目与“next”条目进行比较,但让循环一直运行到最后,它应该是结束-1。是的,调试器应该把你放在那条线上。
-
一些关于风格的建议。首先,编译器为
Employee生成了一个赋值运算符,因此交换代码中的详细赋值可以用buff1 = employees10[count+1];等更简单的赋值操作符代替。其次,您可以只用一个临时值交换两个值。第三,你可以用std::swap交换两个值。
标签: c++ arrays file sorting bubble-sort