C++ “如何排序”;向量";哪些包含类对象?为什么我错了?

C++ “如何排序”;向量";哪些包含类对象?为什么我错了?,c++,stl,C++,Stl,今天我写了一些关于使用std::sort()操作包含类对象的“vector”类型的代码,但我发现编码中存在很多问题,请帮助我找到解决方案: #include <vector> #include <algorithm> class Obj{ private: int m_; public: Obj():m_(0) {} int act() { return m_; } bool operator<(Obj obj) {

今天我写了一些关于使用std::sort()操作包含类对象的“vector”类型的代码,但我发现编码中存在很多问题,请帮助我找到解决方案:

#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;
}
#包括
#包括
Obj类{
私人:
int m_;
公众:
Obj():m_0{}
int act(){return m_;}
布尔运算符act()
@1:为什么参数的类型必须是“Obj”而不是“const Obj&”?但是当“Obj”是一个结构类型时,它不会出错,为什么


@3:我在使用
std::sort
时重载了操作符“,您可以像您一样随意传递比较器。如果不这样做,
std::sort
将使用
std::less
作为比较器,
std::less
默认使用
运算符
应该是

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

bool操作符act()
应该是

int act() const { return m_; }
bool operator<(const Obj& obj) const {
    return this->act() < obj.act();
}
bool操作符act()
谢谢!我想我应该更仔细地检查编译器消息!
bool operator<(const Obj& obj) const {
    return this->act() < obj.act();
}