Reputation: 458
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++
Upvotes: 1
Views: 94
Reputation: 275385
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.
Upvotes: 3