设置操作不适用于自定义对象

Set operations not working for Custom Object

所以我有一个名为 WaterJug 的自定义对象,在全局 set<WaterJug>:

上调用函数时出现错误

这是在class定义之前定义的:

set<WaterJug> memo;

并且在我的 class 的方法之一中:

for(std::vector<WaterJug>::iterator newJug = newJugs.begin(); newJug != newJugs.end(); ++newJug) {
    const bool is_in = memo.find(newJug); //error here
    if (is_in) {

    }
}

错误是:No matching member function for call to 'find'

我是否必须在我的自定义 class 中实现任何接口才能使设置操作生效?

std::set::find取一个对象,newJug是一个迭代器,不是对象,要通过迭代器访问对象"pointed",需要解引用newJug : *newJug:

此外,find returns 是一个迭代器,而不是 bool,它 returns end() 未找到对象 os 的迭代器。

这个版本的代码可以工作:

for(std::vector<WaterJug>::iterator newJug = newJugs.begin(); newJug != newJugs.end(); ++newJug) {
    const bool is_in = ( memo.find(*newJug) != memo.end() );
    if ( is_in ) {

    }
}

std::set::find 只接受集合的 key 类型的参数。当您使用 memo.find(newJug) 时,您是在调用 find 时使用指向 key 而不是 key 的迭代器。您可以取消引用迭代器以获取键值 memo.find(*newJug);.

您还有一个问题,即当 find return 是迭代器时,您试图将查找中的 return 存储为 bool。如果你想知道 find 是否找到了一些东西,那么你可以重写

const bool is_in = memo.find(newJug);

const bool is_in = (memo.find(newJug) != memo.end());

你有几个错误。

  1. 传递给 memo.find 的参数错误。

    memo.find(newJug) // tpe of newJug is an iterator, not an object.
    

    需要

    memo.find(*newJug)
    
  2. memo.find() 的 return 值不是 bool。它是一个迭代器。而不是

    const bool is_in = memo.find(newJug); //error here
    if (is_in) {
    

    使用:

    if ( memo.find(*newJug) != memo.end() )