gpt4 book ai didi

c++ - 在用户定义的对象上调用 std::find 时出错

转载 作者:行者123 更新时间:2023-11-30 04:18:13 26 4
gpt4 key购买 nike

所以我一直收到错误消息:

no match for 'operator==' in '(&__first) >std::_List_iterator<_Tp>::operator* with _Tp = Course == __val'

在下面的代码中:

int main(){
Course NOT_FOUND("NOT_FOUND", "NOT_FOUND", 0);
Course x("COMP2611", "COMPUTER ORGANIAZTION", 2);
HashTable<Course> q(NOT_FOUND, 17, 36);

q.insert(x);
}



template <class HashedObj>
class HashTable{
public:
HashTable(const HashedObj& notFound, int bucket, int base);
void insert(const HashedObj& x);

private:
const HashedObj ITEM_NOT_FOUND;
vector<list<HashedObj> > theList;
};

template <class HashedObj>
void HashTable<HashedObj>::insert(const HashedObj& x){
list<HashedObj>& whichList = theList[hash(x)];
typename list<HashedObj>::iterator itr;
itr = std::find(theList[0].begin(), theList[0].end(), x);
if(itr == theList[hash(x)].end())
whichList.insert(theList[hash(x)].begin(), x);
}

我测试了一下,发现错误来自那行

itr = std::find(theList[0].begin(), theList[0].end(), x);

但我不知道该怎么做才能修复它。我想我只是在打电话标准查找功能在这里,但显然它不起作用。

类(class)类(class)我认为是正确定义的,因为我之前在其他类(class)中测试过。

代码是:

class Course{
public:
Course(string code, string name, int credit):
_code(code), _name(name), _credit(credit){}

string _code;

private:
string _name;
int _credit;

friend int hash(Course x);
};


int hash(Course x){
int sum = 0;
for(int i = 0; i < x._name.size(); i++)
sum+=_name[i];

return sum % 35;
}

最佳答案

find 使用 operator== 将您要查找的参数与迭代器的值进行比较。您的 Course 类没有这样的 operator==。您需要实现它。

class Course {
public:
// bla bla
friend
bool operator==(const Course& x, const Course& y)
{ return your-comparison-code-here; }
};

正如 James Kanze 指出的那样:您还可以使用 std::find_if 并提供比较仿函数/lambda。

关于c++ - 在用户定义的对象上调用 std::find 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16544950/

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