简体   繁体   中英

C++ How to do 2 Sort and merge result into 1

Parent Class:

Character

Sub class:

Elf
Human

I have a variable which is

int myScore;
string myType;

so what i did was to sort by myType then sort by ascending score

means if i got record like this

[1] Human, 99
[2] Elf, 91
[3] Elf, 99
[4] Human, 99

If sort it will be

[1] Human, 90 
[2] Human, 99
[3] Elf, 91
[4] Elf, 99

I heard before the merge function that can merge 2 sort into 1.

But how do i use it.

What i did for now is

At character.cpp

struct sort_by_score
{
    static bool operator()(Character* x, Character* y)
    {
        return x->getScore() < y->getScore();
    }
};

At main.cpp

I did this

int main()
{
Character *chara[100];
vector<Character*> sortVector;

//some input of value here.. assuming now got 4 pointers to object, 2 human 2 elf. 

sortVector.clear();
sortVector.assign(chara,chara + characterCounter);

//here i got question on how to sort by Human Then Elf

//2nd sort is sort by score
sort(sortVector.begin(), sortVector.end(), sort_by_score());

for (int i=0;i<characterCounter;i++)
{
cout << sortVector.toDisplay() << endl;
}

return 0;
}

Thanks for all help!!

You could also do this very easy with lambdas (C++0x/11):

vector<Character> v = ...;

sort(v.begin(), v.end(), [](const Character &lhs,const Character & hs){
    return lhs.getType() == rhs.getType() ? lhs.getScore() < rhs.getScore()
                                          : lhs.getType() < lhs.getType();
});

Or for pointers:

vector<Character*> v = ...;

sort(v.begin(), v.end(), [](const Character *lhs,const Character * hs){
    return lhs->getType() == rhs.getType() ? lhs->getScore() < rhs->getScore()
                                           : lhs->getType() < lhs->getType();
});

I couldn't find a "criteria combiner" so I wrote one on my own. This should work:

template<class T, class First, class Second>
class combine {
    First first;
    Second second;
public:
    bool operator()(const T & lhs, const T & rhs) const {
        if(first(lhs, rhs)) return true;
        if(first(rhs, lhs)) return false;
        return second(lhs, rhs);
    }
};

With two basic comparison functors

struct less_type
{
    static bool operator()(const Character & lhs, const Character & rhs) {
        return lhs.getType() < rhs.getType();
    }
};
struct less_score
{
    static bool operator()(const Character & lhs, const Character & rhs) {
        return lhs.getScore() < rhs.getScore();
    }
};

this can be used like the following:

vector<Character*> v = ...;

sort(v.begin(),v.end(), combine<Character,less_type,less_score>());

This will also work without support for C++0x lambdas.

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