sort排序算法

#include<bits/stdc++.h>
using namespace std;
int main (){
    vector<int> num{3,1,2,4,7,6,5,8};
    //默认排序 
    sort(num.begin(),num.end());
    cout<<"升序";
    for(int n:num) cout<<n<<" "; 
    //降序排序 
    sort(num.rbegin(),num.rend());
    cout<<"降序";
    for(int n:num) cout<<n<<" "; 
    
    
    return 0;
}

 

#include <bits/stdc++.h>
using namespace std;
bool www(string &a,string &b){
    return a.size()<b.size();
}
int main(){
    vector <string> s={"asdasda","ggaggagaqq3","agagwfWT"};
    sort(s.begin(),s.end(),www);
    cout<<"长度升序";
    for(string i:s){
        cout<<i<<" ";
    }
    sort(s.rbegin(),s.rend(),www);
    cout<<"长度降序";
    for(string i:s){
        cout<<i<<" ";
    }
    return 0; 
}

 

#include <bits/stdc++.h>
using namespace std;
struct Tom{
    string name;
    int age;
    int score;
};
bool score_1(const Tom &a,const Tom &b){
    if(a.score==b.score){
        return a.age<b.age;
    }else{
        return a.score<b.score;
    }
}
int main(){
    vector <Tom> s={{"Tom硕",500,16},
                    {"Lucy博",588,15},
                    {"Tonny恒",463,17},
                    {"Jack硕",661,14},
                    };
    sort(s.begin(),s.end(),score_1);
    cout<<"长度升序"<<endl;
    for(auto &i:s){
        cout<<i.name<<" "<<i.score<<" "<<i.age<<endl;
    }
    sort(s.rbegin(),s.rend(),score_1);
    cout<<"长度降序"<<endl;
    for(auto &i:s){
        cout<<i.name<<" "<<i.score<<" "<<i.age<<endl;
    }
    return 0; 
}

 

posted @ 2025-07-26 14:59  郭立恒  阅读(3)  评论(0)    收藏  举报