结构数组的第一个元素在排序后变为 nill

Struct array's first element become nill after sorting

本文关键字:nill 排序 数组 第一个 元素 结构      更新时间:2023-10-16

我编写代码从文本文件中读取学生姓名和他们的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;
      }
}