Question

I have a real headache with my sorting method. I don't know what can be wrong? I have checked sorting method millions of times and I still messed up with it. Here are my code

struct Man{
    string name;
    string adress;

    bool operator < (const Man & next);
};

bool Man::operator < (const Man & next){
    return adress < next.adress && name < next.name;
}

struct SarV{
    Man duom;
    SarV *sekV;
};

struct SarH{
    string date;
    SarH *sekH;
    SarV *prV;
};

void Branch::Check(string code, int month){
    ofstream rf("Rezultatai.txt", ios::app);
    rf.setf(ios::left);
    SarH *d = pr;
    rf << "Data" << endl;
    while(d != NULL){
        SarV *v = d->prV;
        Print(rf, v, code, month);
        d = d->sekH;
    }
    rf.close();
}

Here are my sorting function

void Branch::Sort(){
    string temp;
    for(SarH *s = pr; s != NULL; s = s->sekH){
        for(SarV *p = s->prV; p != NULL; p = p->sekV){
            for(SarV *p2 = p; p2 != NULL; p2 = p2->sekV){
                if(p2->duom < p->duom){
                    //---------------------------------------
                    temp = p->duom.name;
                    p->duom.name = p2->duom.name;
                    p2->duom.name = temp;
                    //---------------------------------------
                    temp = p->duom.adress;
                    p->duom.adress = p2->duom.adress;
                    p2->duom.adress = temp;
                    //---------------------------------------
                }
            }
        }
    }
}

So what's wrong with it?

Was it helpful?

Solution

Your operator is likely wrong.

Try this:

bool Man::operator < (const Man & next){
    if(adress < next.adress) return true;
    if(adress == next.adress) {
       if(name < next.name) return true;
    }
    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top