【问题标题】:Error when calling std::find on a user-defined object在用户定义的对象上调用 std::find 时出错
【发布时间】:2013-05-08 20:07:33
【问题描述】:

所以我不断收到错误消息:

'(&__first) >std::_List_iterator<_tp>::operator* 中的 'operator==' 与 _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 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;
}

【问题讨论】:

    标签: c++ iterator find hashtable operator-keyword


    【解决方案1】:

    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。

    【讨论】:

    • 另外,他可以使用find_if,并提供一个比较器。
    • 非常感谢你们,这很有帮助!
    • @user1819047 如果此答案解决了您的问题,请单击复选标记接受。还可以查看 faq 以了解 stackoverflow。
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 2013-05-14
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多