1

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++

6
  • 4
    Do you mean sort? Commented Jul 22, 2016 at 18:28
  • yes sorr will edit Commented Jul 22, 2016 at 18:28
  • std::swap perhaps Commented Jul 22, 2016 at 18:29
  • 3
    Do you want something that sorts properly, or something that's equivalent to what you posted? You're clobbering v[4], sorting doesn't do that. Commented Jul 22, 2016 at 18:30
  • i was asking the best and easiest way to sort , cuz the code i post above its not the best solution i ges Commented Jul 22, 2016 at 18:33

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

But the poster is not swapping the rest of the structure
@yahoo5000 live example - I have no idea what compiler jsfiddle uses for C++ code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.