sort排序
任务一:选第k大的元素
#include<bits/stdc++.h>//任务:选第k大的元素 using namespace std; int main(){ vector<int>a={1,9,2,6,7,8}; //方法一:从小到大排序(默认) sort(a.begin(),a.end()); int k; cin>>k; cout<<a[a.size()-k]<<endl; //方法二:从大到小排序 sort(a.begin(),a.end(),greater<int>()); for(int i=0;i<a.size();i++){ cout<<a[i]<<'\t'; } cout<<'\n'<<a[k-1]; return 0; }
任务二:struct类型的排序
#include<bits/stdc++.h>//struct排序 using namespace std; struct s{ int grade; int age; string name; }; //方法一:用函数 bool com(s&a,s&b){ return a.age>b.age;//按年龄降序 } int main(){ vector<s>student; int x,y; string z; for(int i=0;i<4;i++){ cin>>x>>y; cin>>z; s d; d.grade=x; d.age=y; d.name=z; student.push_back(d); } sort(student.begin(),student.end(),com);//用函数名com for(int i=0;i<4;i++){ cout<<student[i].age<<","<<student[i].grade<<","<<student[i].name<<endl; } return 0; }
方法二:在结构体里重载
#include<bits/stdc++.h>//struct排序
using namespace std;
struct s{
int grade;
int age;
string name;
bool operator<(const s&a) const{//标红部分固定
return grade>a.grade;//按成绩降序
}
};
int main(){
vector<s>student;
int x,y;
string z;
for(int i=0;i<4;i++){
cin>>x>>y;
cin>>z;
s d;
d.grade=x;
d.age=y;
d.name=z;
student.push_back(d);
}
sort(student.begin(),student.end());
for(int i=0;i<4;i++){
cout<<student[i].age<<","<<student[i].grade<<","<<student[i].name<<endl;
}
return 0;
}
#include<bits/stdc++.h>//struct排序 using namespace std; struct s{ int grade; int age; string name; }; bool com(s&a,s&b){ return a.age>b.age; } struct Cmp{ bool operator()(s&a,s&b){//按分数升序,operator()固定 return a.grade<b.grade; } }; int main(){ vector<s>student; int x,y; string z; for(int i=0;i<4;i++){ cin>>x>>y; cin>>z; s d; d.grade=x; d.age=y; d.name=z; student.push_back(d); } sort(student.begin(),student.end(),Cmp());//这里面写结构体排序() for(int i=0;i<4;i++){ cout<<student[i].age<<","<<student[i].grade<<","<<student[i].name<<endl; } return 0; }方法三再定义一个结构体作为排序
任务三:对学生成绩进行排名同分同名
#include<bits/stdc++.h>//struct排序
using namespace std;
struct s{
int grade;
int age;
string name;
int rank;
bool operator<(const s&a) const{
return grade>a.grade;
}
};
int main(){
vector<s>student;
int x,y;
string z;
for(int i=0;i<4;i++){
cin>>x>>y;
cin>>z;
s d;
d.grade=x;
d.age=y;
d.name=z;
student.push_back(d);
}
sort(student.begin(),student.end());
int l=1;//控制排名
student[0].rank=l;
for(int i=0;i<4;i++){
cout<<student[i].age<<","<<student[i].grade<<","<<student[i].name<<endl;
if(student[i].grade<student[i-1].grade){
l++;
}
student[i].rank=l;
}
cout<<"--------------------"<<endl;
for(auto i:student){
cout<<i.name<<'\t'<<i.rank<<'\n';
}
return 0;
}