gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:38:50 26 4
gpt4 key购买 nike

通常当我执行 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
}

binary "==" no operator found which takes a left-handed operand of type RenderJob (or there is no acceptable conversion)

编辑:谢谢您的回答。以下是它失败原因的一些示例

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

std::vector<RenderJob> renderJobs;

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

*constit == foo2; // Doesn't work

更简单的例子:

 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.

如果反过来:

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

最佳答案

你离开了你的 const 限定符。

bool operator==(const RenderJob& rhs) const { ... }

关于c++ - 为什么这个 std::find 不能比较这些对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46439325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com