Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;vector std::find()和自定义类的vector_C++_Vector_Find - Fatal编程技术网

C++ C++;vector std::find()和自定义类的vector

C++ C++;vector std::find()和自定义类的vector,c++,vector,find,C++,Vector,Find,为什么以下方法不起作用 MyClass *c = new MyClass(); std::vector<MyClass> myVector; std::find(myVector.begin(), myVector.end(), *c) MyClass*c=newmyclass(); std::vector myVector; std::find(myVector.begin(),myVector.end(),*c) 这将带来一个错误。我记不起确切的错误,对此表示抱歉,但它说类似

为什么以下方法不起作用

MyClass *c = new MyClass();
std::vector<MyClass> myVector;
std::find(myVector.begin(), myVector.end(), *c)
MyClass*c=newmyclass();
std::vector myVector;
std::find(myVector.begin(),myVector.end(),*c)
这将带来一个错误。我记不起确切的错误,对此表示抱歉,但它说类似MyClass和const MyClass的内容无法由运算符进行比较==

但是,如果我对非类数据类型而不是“MyClass”执行相同的操作,那么一切都可以正常工作。
那么如何正确地使用类来实现这一点呢?

除非重载运算符==来提供这样的函数,否则无法比较自己类类型的两个对象。std::find()使用重载运算符==比较默认提供的迭代器范围内的对象。

std::find的文档来自:

模板
输入计算器查找(输入计算器第一,输入计算器最后,常量T&val)

在范围内找到值 向[first,last]范围内比较等于val的第一个元素返回迭代器。如果未找到此类元素,则函数返回last

该函数使用
运算符==
将各个元素与val进行比较

编译器不会为类生成默认的
运算符==
。您必须对其进行定义,才能对包含类实例的容器使用
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.
}
A类
{
INTA;
};
B类
{
bool操作符==(const&rhs)const{返回this->b==rhs.b;}
int b;
};
void foo()
{
std::向量表;
A A;
std::find(aList.begin(),aList.end(),a);//不正常。a::operator==不存在。
std::向量bList;
B B;
std::find(bList.begin(),bList.end(),b);//OK.b::operator==存在。
}

您是否为您的类重载了
运算符==
?不,我没有,这实际上是个问题,谢谢!@CaptainObvlious:
运算符==
从未为类类型隐式定义/自动生成。如果它是隐式定义的,至少对于POD来说是这样的。缺少它意味着很容易使用memset-memcmp比较structs.Oops。出于某种原因,我认为这是一个复制赋值运算符。谢谢你的回答!这对我来说很有意义!