冒泡在包含名称和标记的结构中按升序对名称进行排序

Bubble sort names in ascending order in a structure containing name and marks

本文关键字:升序 排序 包含名 结构      更新时间:2023-10-16

当我调用函数然后显示它时,输出与输入相同。程序中没有其他错误,这应该意味着函数中存在一些问题。我只是一个初学者,所以任何帮助不胜感激。

#include <iostream>
using namespace std;
struct student
{
   char name[30];
   int marks;
   void getinfo()
   {
       cout<< "Enter your name:n"; cin>>name;
       cout<<"Enter marks:n"; cin>>marks;
   }
   void showinfo()
   {
       cout<<"nName: "<<name<<endl;
       cout<<"Marks: "<<marks<<endl<<endl;
   }
};

void bubsort( student S[] , int N)
{
    student Temp;
    for(int i=0;i<N-1;i++)
    for(int j=0;j<N-1-i;j++)
{
    if(S[j].name>S[j+1].name)
    {
        Temp=S[j];
        S[j]=S[j+1];
        S[j+1]=Temp;
    }
  }
}

int main()
{
    student A[5];
    cout<<" Enter details for 5 students:n";
    for( int i=0;i<5;i++)
    A[i].getinfo();
    bubsort(A,5); //I used the function
    cout<<" Sorted information:n";
    for( int j=0;j<5;j++)
    A[j].showinfo();  //result is in the same order as input
}
数组衰减

为指针,因此您的比较S[j].name>S[j+1].name是比较指针而不是字符串。

如果要比较字符串,则需要使用std::string而不是字符数组,或者使用strcmp