How to use std::find() with vector of custom class?(如何对自定义类的向量使用std::find()?)
本文介绍了如何对自定义类的向量使用std::find()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下选项不起作用?:
MyClass c{};
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), c);
这将产生错误。
但是,如果我对非类数据类型(而不是MyClass";)执行相同的操作,则一切工作正常。 那么,如何正确处理类呢?错误:‘Operator==’不匹配(操作数类型为‘MyClass’和‘const MyClass’)
推荐答案
文档std::find来自http://www.cplusplus.com/reference/algorithm/find/:
在范围内查找值 返回范围[First,Last]中与val相等的第一个元素的迭代器。如果找不到这样的元素,则该函数返回LAST。
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
编译器不会为类生成默认的该函数使用
operator==将单个元素与val进行比较。
operator==。您必须定义它才能对包含类实例的容器使用std::find。
class A
{
int a;
};
class B
{
bool operator==(const& rhs) const { return this->b == rhs.b;}
int b;
};
void foo()
{
std::vector<A> aList;
A a;
std::find(aList.begin(), aList.end(), a); // NOT OK. A::operator== does not exist.
std::vector<B> bList;
B b;
std::find(bList.begin(), bList.end(), b); // OK. B::operator== exists.
}
这篇关于如何对自定义类的向量使用std::find()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何对自定义类的向量使用std::find()?
基础教程推荐
猜你喜欢
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
