How to sort & ldquo; vector & rdquo; which contains class objects? And why am I wrong?

advertisements

Today I wrote some codes about using std::sort() to operate a "vector" type which contains class objects, but I found many problems in coding, please help me to find solution:

#include <vector>
#include <algorithm>

class Obj{
private:
    int m_;
public:
    Obj():m_(0) {}
    int act() { return m_; }
    bool operator<(Obj obj) {
        return this->act() < obj.act();
    }
};
bool cmp(Obj a, Obj b)
{
    return a.act() < b.act();
}
bool cmpA(const Obj& a, const Obj& b)
{
    return a.act() < b.act(); // @1 but wrong!
}
int foo()
{
    std::vector<Obj> vobj;
    // ...
    std::sort(vobj.begin(),vobj.end(),cmp); // @2 well, it's ok.
    std::sort(vobj.begin(),vobj.end());     // @3 but wrong!
    return 0;
}

@1: Why the type of param must be 'Obj' rather than 'const Obj&'? But when 'Obj' is a struct type, it would not come to an error, why?

@3: I had overload the operator '<', but here can not pass while compling. Had I missing something? Please help me, thanks!


When using std::sort you can optionally pass a comparator, like you do. If you don't, std::sort will use std::less as a comparator, std::less defaults to use operator<.

You can use your cmpA functor, but then you can only access const member functions of the passed objects - you have a const reference to them in cmpA.

class Obj{
private:
    int m_;
public:
    Obj():m_(0) {}
    int act() const { return m_; } // const member function, can be called on const objects or references
}; 

bool operator<(Obj const & L, Obj const & R) { // The operator takes const references - it can compare const objects
    return L.act() < R.act();
}

Using this class and operator, you can call std::sort without passing a comparator.