开发者

How to sort "vector" which contains class objects? And why I am wrong?

开发者 https://www.devze.com 2023-02-17 23:52 出处:网络
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:

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.


int act() { return m_; }

should be

int act() const { return m_; }

and

bool operator<(Obj obj) {
    return this->act() < obj.act();
}

should be

bool operator<(const Obj& obj) const {
    return this->act() < obj.act();
}
0

精彩评论

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

关注公众号