C++ std:sort() using different criteria

1.8k Views Asked by At

I searched a lot and I am not sure if this is query is repeated but I used this as an reference to create a sort for my std::vector which takes data of following type.

typedef struct {
    int size;
    int type;
    int id;
} AC; 

I was able to write individual function objects for each criteria. However, my project requirement says that I need to have only once class or struct to include all the function objects for sorting according to size,type and id. Is it possible to have all the function objects for std::sort in one class?

I mean something like

Comparator com;
sort(iVec.begin(),iVec.end(),com.sortbysize);
sort(iVec.begin(),iVec.end(),com.sortbytype);
sort(iVec.begin(),iVec.end(),com.sortbyid);

I also looked at binary_functions to fulfill my requirement but I was getting errors, when I declared more than one function object in a single class.

Further, is it necessary that function objects for std::sort (and for that matter any STL algorithm which involves comparison) need to be bool operator() or they can be normal functions returning bool?

2

There are 2 best solutions below

1
On BEST ANSWER

Yes to both:

struct Comparator
{
    static bool sortbysize(const AC &lhs, const AC &rhs) { /*...*/ }
    static bool sortbytype(const AC &lhs, const AC &rhs) { /*...*/ }
    static bool sortbyid(const AC &lhs, const AC &rhs) { /*...*/ }
}
0
On

Yes, if you want to have a class, you can define static functions on it:

class MyComparator {
    public:
        static bool sortbysize( const AC & elem1, const AC & elem2 ){ ... }
        static bool sortbytype( const AC & elem1, const AC & elem2 ){ ... }
        static bool sortbyid  ( const AC & elem1, const AC & elem2 ){ ... }
}

And then using sort using the appropriate syntax for invoking static functions:

sort(iVec.begin(),iVec.end(),MyComparator::sortbysize);

If you really prefer to follow a regular comparable class style, you can do (although appears to be a bit stupid) things like using a static marker inside the class that specifies how the comparison operator will work:

typedef struct {
    int size;
    int type;
    int id;

    enum marker { SIZE, TYPE, ID };
    static AC::marker comparisonType;

    bool operator() (const AC & i,const AC & j) 
    { 
        // Work here to make the enum thing work with the switch-case... 
        // it's all about integers
        switch(AC::comparisonType){
        case SIZE:
            return (i.size < j.size);
        ...
        }
    }
} AC;