//练习要求:输入10个学生的姓名和年龄,按年龄的从大到小显示学生信息
//练习步骤:建立结构体Student{name,age},输入单个学生信息,打印学生信息
//练习冒泡排序,练习结构体指针对象的使用和排序
//练习要求:输入10个学生的姓名和年龄,按年龄的从大到小显示学生信息
//练习步骤:建立结构体Student{name,age},输入单个学生信息,打印学生信息
//练习冒泡排序,练习结构体指针对象的使用和排序
#include <iostream>
using namespace std;
//定义结构体
struct Student{
string name;
int age;
} ;
//基础排序练习,熟悉排序,复习基础代码
void sort(){
int arr[5]={1,5,8,4,6};
cout<<"打印数组"<<endl;
for(int i=0;i<5;i++){
cout<<arr[i]<<"";
} cout<<endl;
int t=0;
for(int i=0;i<5;i++){
//冒泡大循环,每轮比出一个最大数,放在最;
for(int j=0;j<5-i;j++){
//小循环,两两相比直接,把数值大的往右放
if(arr[j]>arr[j+1]){
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
cout<<"排序后,打印数组"<<endl;
for(int i=0;i<5;i++){
cout<<arr[i]<<"";
}
cout<<endl;
}
//定义排序,给定结构体指数数组和排序的个数,冒泡排序
void StuSort(Student* stu[],int n)
{
//stu[0]->name ,age;
// 按年龄从大到小排序
cout<<"启动排序";
for(int i=0;i<n;i++){
// 大循环,每次推出一个最大数
for(int j=0;j<n-i;j++){
//交换最大的数
if(stu[j]->age>stu[j+1]->age){
//交换指针数组的对象,封装成函数调用
swap(stu[j],stu[j+1]);
}
}
}
}
// 交换两个结构体元素的函数
void swap(struct Student *a, struct Student *b) {
struct Student temp = *a;
*a = *b;
*b = temp;
}
//打印输出数组
void SPrint(Student* stu[],int n){
//输出信息
cout<<"打印学生信息"<<endl;
for(int i=0;i<=n;i++){
cout<<"name:"<<stu[i]->name<<" age:"<<stu[i]->age<<" |";
}
cout<<endl;
}
int main(){
sort(); //复习基础冒泡代码
//单个学生信息的处理
Student* s1=new Student;
s1->age=10;
s1->name="abc";
cout<<s1->name<<s1->age<<endl;
Student* stu[5];
// 输入学生信息
cout<<"请录入5个学生信息name和age";
for(int i=0;i<5;i++){
stu[i]=new Student;
cout<<"输入第"<<i+1<<"个"<<endl;
cin>>stu[i]->name>>stu[i]->age;
cout<<endl;
}
// // 输出信息
// for(int i=0;i<=9;i++){
// cout<<"name:"<<stu[i]->name<<" age:"<<stu[i]->age<<endl;
// }
//多次调用直接封装成函数
SPrint(stu,5); //打印学生信息
//按年龄排序
StuSort(stu,5);
SPrint(stu,5); //打印学生信息
}