sort排序

Annaprincess發表於2024-08-29

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;
}

sort排序
#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;
}

相關文章