结构数组的第一个元素在排序后变为 nill
Struct array's first element become nill after sorting
我编写代码从文本文件中读取学生姓名和他们的CGPA,并将它们保存在类型结构的数组中,然后根据CGPA按升序排序。排序后数组的第一个元素为空,为什么?
类型学生的结构
struct student{
char name[20];
float cgpa;
};
读取文件的代码
while(!inFile.eof()){
inFile>>students[i].name >> students[i].cgpa;
cout << i << "t" << students[i].name << "tt" << students[i].cgpa << endl;
i++;
}
交换功能,用于根据CGPA按升序对数组内容进行排序。
void swap(student studentsRcrd[]){
student tempValue;
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
if(studentsRcrd[j].cgpa > studentsRcrd[j+1].cgpa){
tempValue = studentsRcrd[j];
studentsRcrd[j] = studentsRcrd[j+1] ;
studentsRcrd[j+1] = tempValue;
}
}
}
}
命令提示符的最终输出
No Name CGPA
0 ▄ 0
1 Maria 2.4
2 Humza 2.6
3 Saira 2.6
4 Anila 3
5 Junaid 3
6 Usman 3.4
7 Aasim 3.5
8 Talaal 3.8
9 Haris 3.9
10 Ahmer 4
Swap函数必须看起来像这个
void swap(student studentsRcrd[]){
student tempValue;
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(studentsRcrd[j].cgpa > studentsRcrd[j+1].cgpa){
tempValue = studentsRcrd[j];
studentsRcrd[j] = studentsRcrd[j+1] ;
studentsRcrd[j+1] = tempValue;
}
}
}
}
因为当j==10时,studentsRcrd[j+1]将是studentsR crd[11],并且在这个位置上没有放任何东西,所以它有零,所以当排序函数将这个零放在顶部时,因为它的值最小,然后按升序打印。因此,将环路条件更改为
i < 9
和
j < 9
您有10个成员的数据!这是0到9。但是当你使用
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
当j == 9
时,它将与下一个内存位置(j = 10
)交换数据,这不在您的范围内!试试这个-
for(int i=0; i<9; i++){ // Make i<9 and j<9
for(int j=0; j<9; j++){ // when j == 9, it will swap the data with next memory location
if(studentsRcrd[j].cgpa > studentsRcrd[j+1].cgpa){
tempValue = studentsRcrd[j];
studentsRcrd[j] = studentsRcrd[j+1] ;
studentsRcrd[j+1] = tempValue;
}
}
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 结构数组的第一个元素在排序后变为 nill