结构体排序(按照年龄进行排序)
一、先说一下sort的用法
头文件是
#include<algorithm>
我用的是万能头文件,这里说一下,有些编译器用不了万能头文件.
#include<bits/stdc++.h>
using namespace std;
int main()
{
//实现排序问题,sort函数
srand((unsigned int)time (NULL));
int a[10]={0};
for(int i=0;i<10;i++)
{
a[i]=rand()%10+1;//这里生成1~10随机数
}
for(int i=0;i<10;i++){
cout<<a[i]<<" ";
}cout<<endl;
//sort进行排序
sort(a,a+10);
for(int i=0;i<10;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
下面是运行结果
了解了sort的用法,接下来看一下用sort的强大之处吧
#include<bits/stdc++.h>
using namespace std;
struct T{
string name;
int age;
string sex;
bool operator<(const T &that)const//这里进行了结构体内部的重载<
{
return age>that.age;
}
};
//bool cmp(T x,T y)
//{
// return x.age>y.age;
//}
void test(struct T t[],int n)
{
for(int i=0;i<n;i++)
cin>>t[i].name>>t[i].age>>t[i].sex;
//sort(t,t+n,cmp);注释部分是第二中方法
sort(t,t+n);
for(int i=0;i<n;i++){
cout<<t[i].name<<" "<<t[i].age<<" "<<t[i].sex<<endl;
}
}
int main() {
T t[5];
test(t,5);
return 0;
}
下面是运行结果: