Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort entire struct array based on gc value

Tags:

c++

arrays

struct

How do i go about sorting the entire struct and all its elements in the array based on double gc from lowest to highest?

I have no idea where to begin, and have been struggling for hours.

struct DNA
{
    vector <string>header;
    string DNAstrand;
    double gc;
    int valid; // 0 not valid | 1 valid
};
struct World
{
    //  int     numCountries;
    DNA dnas[MAX_DNA_SIZE];
} myWorld;

Basically my goal is to arrange all the elements in sync using gc lowest to highest, so if i pull myWorld.dnas[2].valid or so itll correlate to its gc once sorted.

like image 758
soniccool Avatar asked Aug 02 '26 07:08

soniccool


2 Answers

That's rather easy with C++11 and std::sort:

std::sort(std::begin(myWorld.dnas), std::end(myWorld.dnas), [](const DNA& dna1, const DNA& dna2) { return dna1.gc < dna2.gc; });
like image 84
Jack Avatar answered Aug 03 '26 21:08

Jack


Since you don't seem to have C++11, you can try the following:

#include <algorithm>

int main()
{
    struct
    {
        bool operator()( DNA const& a, DNA const& b )
        {
            return a.gc < b.gc;
        }
    } dna_comparer;

    std::sort( myWorld.dnas, myWorld.dnas + MAX_DNA_SIZE, dna_comparer );
}
like image 44
user2296177 Avatar answered Aug 03 '26 23:08

user2296177



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!