Tanvir
Tanvir

Reputation: 51

Sort stl vector containing template user defined class in decending order using function object

I am facing an issue while sorting a vector of user defined object. I am using the sort algo defined by stl and passing it my function object but it refuses to compile, would you please help me with this.

Thanks.

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

template<typename T>
class MyType
{
    public:
    T t1;
    public:
    MyType()
    {

    }
    MyType(const MyType& mt)
    {
        t1 = mt.t1;
    }
    MyType& operator=(const MyType& mt)
    {
        this->t1 = mt.t1;
        return *this;
    }
    bool operator<(const MyType& mt)
    {
        if(this->t1 < mt.t1)
            return true;
        else
            return false;
    }
    bool operator==(const MyType& mt)
    {
        if(this->t1 == mt.t1)
            return true;
        else
            return false;
    }
    MyType(T t)
    {
        t1 = t;
    }
};

template<class T>
class cmp_greater
{
    public:
    bool operator()(const T& a, const T& b)
    {
        return !(a < b);
    }
};

int main()
{
    MyType<int> m1(1);
    MyType<int> m2(2);
    MyType<int> m3(3);

    vector<MyType<int> > vmt;

    vmt.push_back(m1);
    vmt.push_back(m2);
    vmt.push_back(m3);

    vector<MyType<int> >::iterator pos;

    for(pos = vmt.begin(); pos != vmt.end(); pos++)
    {
        cout<<pos->t1<<endl;
    }

    sort(vmt.begin(), vmt.end(), cmp_greater<MyType<int> >() );
    cout<<"After sorting in decending order."<<endl;
    for(pos = vmt.begin(); pos != vmt.end(); pos++)
    {
        cout<<pos->t1<<endl;
    }

    vmt.erase(vmt.begin()+1);

    cout<<"after erase"<<endl;

    for(pos = vmt.begin(); pos != vmt.end(); pos++)
    {
        cout<<pos->t1<<endl;
    }

    //insert can also be used in vectors;
}

Upvotes: 0

Views: 74

Answers (1)

timrau
timrau

Reputation: 23058

bool operator<(const MyType& mt)

It should be declared as const like

bool operator<(const MyType& mt) const

Otherwise, bool cmp_greater::operator()(const T& a, const T& b) cannot call the overloaded less-than operator.

Upvotes: 2

Related Questions