为什么这个std :: find不能比较这些对象

Zeb*_*ish 10 c++ std c++11

通常当我做一个std :: find时,我会把一个谓词作为第三个参数,但这次我认为我的方法不同,我不明白为什么它不起作用.

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

struct RenderJob
{
    RenderJob() {};
    int renderJob_ID;
    bool operator==(RenderJob& rhs) { return rhs.renderJob_ID == this->renderJob_ID; }
};

int main()
{
    RenderJob foo;
    RenderJob foo2;
    foo == foo2; // Works

    std::vector<RenderJob> renderJobs;

    std::find(renderJobs.begin(), renderJobs.end(), foo); // Doesn't work
}
Run Code Online (Sandbox Code Playgroud)

二进制"=="没有找到哪个运算符采用RenderJob类型的左手操作数(或者没有可接受的转换)

编辑::谢谢你的答案.以下是一些失败原因的例子

    RenderJob foo;
    RenderJob foo2;
    foo == foo2; // Works

    std::vector<RenderJob> renderJobs;

    std::vector<RenderJob>::const_iterator constit = renderJobs.begin();

    *constit == foo2;  // Doesn't work
Run Code Online (Sandbox Code Playgroud)

更简单的说明:

 const RenderJob* pToRenderJob;

*pToRenderJob == foo2;  // This fails because the pointed to 
                        // object is const, and cannot call the 
                        // operator== function because the actual function
                        // definition is not const. 
Run Code Online (Sandbox Code Playgroud)

如果是相反的方式:

foo2 == *pToRenderJob; // This would fail because the 
                        // operator==(RenderJob&) the actual argument 
                        // is not const. Very subtle rules
Run Code Online (Sandbox Code Playgroud)

Dút*_*has 14

你离开了你的const资格赛.

bool operator==(const RenderJob& rhs) const { ... }
Run Code Online (Sandbox Code Playgroud)

  • 可以将非const对象提升为const对象.请记住,const只是意味着对象被标记为"您不能修改它",无论对象的实际可修改性如何. (5认同)
  • 两者都应该是常量.当编译器在const数据上寻找运算符时,它将拒绝考虑不保证const行为的运算符. (4认同)
  • 对了谢谢.特别是const RenderJob,而不是函数之后的那个.虽然我没有得到这个,我可以自己比较它们因为运算符==重载,不是std :: find只是使用operator ==函数吗? (2认同)

Jer*_*fin 5

在我看来像一个常量问题.尝试这样的事情:

bool operator==(RenderJob const &rhs) const { 
    return rhs.renderJob_ID == this->renderJob_ID; 
}
Run Code Online (Sandbox Code Playgroud)

做比较你自己工作,因为你只是传递不是临时的普通对象,也不是const限定.有了std::find,比较函数将(至少通常)接收对集合中对象的引用(通常是const限定的),因此它需要能够接收const限定引用.