用辅助数组对结构数组进行关键字排序,有定义:
person *index[100];
index数组存放结构数组元素的地址。如果把index定义改为:
int index[100];
用于存放结构数组元素的下标,可以实现对结构数组的索引排序吗?如何写程序?请你试一试。
可以。关键是通过整型索引数组元素作为下标访问结构数组。表示为:
all[pi[i]].name all[pi[i]].id all[pi[i]].salary
有关程序如下:
#include<iostream> using namespace std; struct person //说明结构类型 { char name[10]; unsigned int id; double salary; } ; void Input( person[], const int ); void Sort( person[], int[],const int ); void Output( const person[], int[],const int ); int main() { person allone[100] ; //说明结构数组 int index[100]; //说明索引数组 int total ; for(int i=0; i<100; i++) //索引数组元素值初始化为结构数组元素下标 index[i]=i ; cout<<"输入职工人数:"; cin>>total; cout<<"输入职工信息:\n"; Input(allone,total); cout<<"以工资做关键字排序\n"; Sort(allone,index, total); cout<<"输出排序后信息:\n"; Output(allone,index,total); } void Input( person all[], const int n ) { int i ; for( i=0; i<n; i++ ) //输入数据 { cout<<i<<":姓名: "; cin>>all[i].name; cout<<"编号: "; cin >> all[i].id; cout<<"工资: "; cin >> all[i].salary ; } } void Sort(person all[], int pi[], const int n) { int i,j; int t; //交换用中间变量 for(i=1; i<n; i++) //以成员salary做关键字排序 { for(j=0; j<=n-1-i; j++) if(all[pi[j]].salary>all[pi[j+1]].salary) //通过索引数组访问结构数组元素 { t=pi[j]; //交换索引数组元素值 pi[j]=pi[j+1]; pi[j+1]= t; } } } void Output(const person all[], int pi[], const int n) { for( int i=0; i<n; i++ ) //输出排序后数据 cout<<all[pi[i]].name<<'\t'<<all[pi[i]].id<<'\t'<<all[pi[i]].salary<<endl; }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
可以。关键是通过整型索引数组元素作为下标访问结构数组。表示为:
all[pi[i]].name all[pi[i]].id all[pi[i]].salary
有关程序如下: