设置自定义对象不工作的操作
Set operations not working for Custom Object
所以我有一个名为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'
我是否必须在自定义类中实现任何接口以使集合操作工作?
你有几个错误。
-
传递给
memo.find
的参数错误。memo.find(newJug) // tpe of newJug is an iterator, not an object.
必须是
memo.find(*newJug)
-
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());
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- QSqlquery prepare()和bindvalue()不工作
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 使 Flutter C/C++ 互操作示例正常工作
- 异步操作的 Asio 处理程序在其同步对应项正常工作时不会调用
- 重载按位 OR('|'),用于链接操作无法按预期工作
- 为什么我的文件/目录操作在Windows上工作正常,但在Linux上不能
- 无法获得新的 tf。在 Tensorflow 中的 Python shell 中工作的操作
- 此数组操作在C++中如何工作
- 这种按位操作是如何工作的
- 类复制操作,它是如何工作的
- 在boost MPL中,如何检查操作是否按预期工作
- 指针上的此操作如何工作
- 设置自定义对象不工作的操作
- 前缀(++x)和后缀(++ +)操作是如何工作的
- 栈push操作实现不工作
- 为什么此内联程序集中的错误操作无法正常工作
- 为什么提取操作不工作
- 由于在返回语句中使用了布尔或操作,因此递归如何对以下代码工作
- BSF操作码不工作