gpt4 book ai didi

c++ - 比较类的 vector 时如何定义运算符 ==?

转载 作者:行者123 更新时间:2023-11-30 01:35:13 24 4
gpt4 key购买 nike

我想使用 function find 在结构 vector (带有属性 x 和 y)中查找元素,

但是我收到没有匹配的运算符== 的错误。我试图重新定义它,但我仍然收到相同的错误消息:

Error: no match for « operator== » (operand types are « const coordenates » and « const coordenates ») { return *__it == _M_value; }

struct coordenates {
int x;
int y;

bool operator ==(const coordenates &a){
if (x == a.x && y == a.y)
{return true;}
return false;
}

bool findInVector(const std::vector<coordenates> &vecOfElements, const int &i, const int &j)
{
bool presence;
coordenates element;
element.x = i;
element.y = j;

if(std::find(vecOfElements.begin(), vecOfElements.end(), element) == vecOfElements.end()) {
presence = false;}
else{presence = true;}
return presence;
}

最佳答案

它作为 const 坐标传递,因此您的 operator== 也必须标记为 const 以匹配:

bool operator ==(const coordenates &a) const

关于c++ - 比较类的 vector 时如何定义运算符 ==?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592263/

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