设置自定义对象不工作的操作

Set operations not working for Custom Object

本文关键字:操作 工作 自定义 对象 设置      更新时间:2023-10-16

所以我有一个名为WaterJug的自定义对象,在全局set<WaterJug>上调用函数时出现错误:

在类定义之前定义:

set<WaterJug> memo;

在我的类的一个方法中:

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'

我是否必须在自定义类中实现任何接口以使集合操作工作?

你有几个错误。

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

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

    必须是

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

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

    使用:

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

std::set::find接受一个对象,newJug是一个迭代器,而不是对象,要访问迭代器"指向"的对象,需要对newJug: *newJug:

解引用。

而且,find返回的是一个迭代器,而不是bool,它返回的是对象os未找到的end()迭代器。

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

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)时,你是用一个指向key而不是key的迭代器来调用find。您可以解引用迭代器以获得键值memo.find(*newJug);

你还有一个问题,当find返回一个迭代器时,你试图将find的返回值存储为bool。如果你想知道find是否发现了什么,那么你可以重写

const bool is_in = memo.find(newJug);

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