简体   繁体   中英

C++ struct or array sorting

Hello i have structure sorting function and now i am just wondering is there are easier way do this :

void Sorting(Sheeps v[],int all){

    for(int a =0; a < all; a++){
        for(int b = a+1; b < all; b++){
            if(v[b].dna_mach_rate > v[a].dna_mach_rate){
                v[4].dna_mach_rate = v[a].dna_mach_rate;
                v[a].dna_mach_rate = v[b].dna_mach_rate;
                v[b].dna_mach_rate = v[4].dna_mach_rate;
            }
        }
    }
    v[4].dna_mach_rate = 0;
}

so this function just run trough structure and replace values if from biggest to smallest , but this is kind a lot of code to do this , so i am wondering if there are functions like "php" or "javascript" ,"ushort" or something similar or the better way to sort array or structure this is how i was doing in "javascript" :

arrayname.sort(function(a, b){return b.speed - a.speed}); 

and almost same in php so i am wondering if there are similar or even better way to sort array or structure in c++

std::sort(v, v+all, [](Sheeps const& lhs, Sheeps const& rhs){
  return lhs.dna_mach_rate < rhs.dna_mach_rate;
});

is sorting in C++ that takes the array v of length all and puts them in order so that the lowest dna_mach_rate goes first.

You need to #include <algorithm> first, naturally. This also uses C++11 features, but C++11 is 5 years old at this point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM