如何对自定义类的向量使用std::find()? [英] How to use std::find() with vector of custom class?

查看:109
本文介绍了如何对自定义类的向量使用std::find()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下选项不起作用?:

MyClass c{};
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), c);

这将产生错误。

错误:‘Operator==’不匹配(操作数类型为‘MyClass’和‘const MyClass’)

但是,如果我对非类数据类型(而不是MyClass";)执行相同的操作,则一切工作正常。 那么,如何正确处理类呢?

推荐答案

文档std::find来自http://www.cplusplus.com/reference/algorithm/find/

template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);

在范围内查找值 返回范围[First,Last]中与val相等的第一个元素的迭代器。如果找不到这样的元素,则该函数返回LAST。

该函数使用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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆