보통 std :: find를 할 때 세 번째 인수로서 술어를 넣을 것입니다. 그러나 이번에는 제가 다르게 할 것이라고 생각했습니다. 왜 작동하지 않는지 이해하지 못합니다.왜이 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
}
이진 "=="어떤 연산자는 형 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
에도 간단하게 실패하는 이유는 다음의 몇 가지 예입니다
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 =='왼쪽 피연산자가'* this'가되도록'operator =='가 선언되어 있지 않기 때문에'* 구성 == foo2' 또는'* pToRenderJob == foo2'를 할 수 없습니다 . 클래스가'void f();'함수를 가지고 있다면 똑같은 것이 될 것입니다 - 당신은'구성 -> f()'또는'pToRenderJob-> f()'를 할 수 없습니다. 하지만 그 함수를'void f() const;'로 변경하면 두 함수 모두 괜찮을 것입니다. – aschepler
감사합니다. 많은 규칙들이 서서히 설정되고 있습니다. – Zebrafish
클래스 내에'renderJob_ID'를 정의해야합니다 :'int renderJob_ID {}'. 초기화되지 않은 객체를 떠나는 것은 조숙 한 최적화입니다. 귀하의 예제에서 foo.renderJob_ID와 foo.renderJob_ID는 * indeterminate value *를 가지고 있고,'std :: vector renderJobs (10)'을 선언하여 10 개의 renderJobs 벡터를 생성하면이 10 개의 모든 객체는 renderJob_ID에 * 불확정 값 *. 따라서 연산자 == 인수에 const를 추가 한 후에도 코드는 계속 작동하지 않습니다. –
Oliv