我想使用結構對數組進行排序(我第一次使用結構)。這個結構獲取一些學生的名字和ID號,問題在於顯示FirstName時顯示其他FirstNames(我使用dev的C++)在C++中對結構進行排序
#include<iostream>
#include<fstream>
#include<conio.h>
#include <sstream>
using namespace std;
struct Student
{
long long int ID;
string FirstName,LastName;
} mystudent[100];
void PrintInformation(Student sEmployee[100],int b)
{
for(int i=0;i<b;i++)
{
cout << "First Name: " << sEmployee[i].FirstName<< endl;
cout << "ID: " << sEmployee[i].ID<< endl;
}
}
void Sort (Student mine);
int main()
{
int n, c, d, temp;
cout << "Enter element: ";
cin>>n;
for(int i=0;i<n;i++)
{
cout << "Enter FirstName "<<i+1<<": ";
cin>>mystudent[i].FirstName;
}
for(int i=0;i<n;i++)
{
cout << "Enter ID "<<mystudent[i].FirstName<<": ";
cin>>mystudent[i].ID;
}
for (int i = 1 ; i <= n - 1; i++)
{
d = i;
while (d > 0 && mystudent[i].ID < mystudent[i-1].ID)
{
temp = mystudent[i].ID;
mystudent[i].ID = mystudent[i-1].ID;
mystudent[i-1].ID = temp;
mystudent[i-1].FirstName=mystudent[i].FirstName;
d--;
}
}
cout<<"Sorted list in ascending order:\n";
PrintInformation(mystudent,n);
getch();
return 0;
}
如果這是實際生產代碼,我會建議[使用std ::排序您陣列(http://stackoverflow.com/questions/15669900/using-sort-in-stl-to- sort-an-array)和[爲你的Student類提供嚴格的小於運算符](http://stackoverflow.com/questions/9336579/overloading-comparison-operators-to-work-with-stl-sort-in- c) - 也可以使用自定義的操作符函數來替代小於等於的操作符。 –
我使用下面的代碼** woolstar **交換名字,但現在它沒有正確排序。 – user2589043
感謝大家,我的問題解決了。 – user2589043