带有自定义类向量的 C++ 向量 std::find() [英] C++ vector std::find() with vector of custom class

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

问题描述

为什么以下不起作用?:

why does the following not work?:

MyClass *c = new MyClass();
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), *c)

这会带来错误.我不记得确切的错误,抱歉,但它说像 MyClass 和 const MyClass 这样的东西不能被 Operator ==

This will bring an error. I cannot remember the exact error, sorry for that, but it said something like MyClass and const MyClass cannot be compared by the Operator==

但是,如果我对非类数据类型而不是MyClass"执行相同的操作,则一切正常.那么如何用类正确地做到这一点?

However if I do the same thing with non-class datatypes instead of a "MyClass", everything works fine. So how to do that correctly with classes?

推荐答案

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

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

在范围内查找值返回指向范围 [first,last) 中第一个元素的迭代器,该元素比较等于 val.如果没有找到这样的元素,函数最后返回.

Find value in range Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.

该函数使用 operator== 将各个元素与 val 进行比较.

The function uses operator== to compare the individual elements to val.

编译器不会为类生成默认的operator==.您必须定义它才能将 std::find 与包含类实例的容器一起使用.

The compiler does not generate a default operator== for classes. You will have to define it in order to be able to use std::find with containers that contain instances of your class.

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.
}

这篇关于带有自定义类向量的 C++ 向量 std::find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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