开发者

How to use existing integer sort to sort integer tuples?

Does anyone know of an efficient algorithm to use an existing 开发者_运维技巧integer sort (such as the STL sort) to sort integer tuples without modifying the existing integer sort. E.g. I want to sort a list of 4 integer tuples. Tuples are in the form: <int,int,int, int>. Again assume the integer sort can only deal with single ints.


You can sort anything you want using existing C++ sorting routine "sort", by just defining your own comparison function, For eg in your case

sort(mytuplearray, mytuplearray + N, mycomp)

where mycomp is

bool mycomp(tuple& a, tuple& b)
{
     //compare however you like
}


If you want to create a lexicographic tuple comparator using a scalar comparator, simply compare the last pair of components that is not equal. Something like this:

template<typename T>
class LexicographicCompare
{
private:

    T Compare;

public:

    LexicographicCompare(T Compare) : Compare(Compare)
    {
    }

    bool operator()
        ( const tuple<int, int, int> & a
        , const tuple<int, int, int> & b
        ) const
    {
        if (a[0] != b[0])
            return Compare(a[0], b[0]);
        if (a[1] != b[1])
            return Compare(a[1], b[1]);
        return Compare(a[2], b[2]);
    }
};

sort(tuples.begin(), tuples.end(), LexicographicCompare(IntCompare()));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜