c++ - 如何在 std::vector 中找到一个对象

标签 c++ vector std

我有一个像下面这样的对象

 class MyClass{
   int a;
   double b;
 };

 vector<MyClass> vMyClass;

然后我想在 vMyClass 中搜索尝试使用算法函数:

 if( std::find(vMyClass.begin(), vMyClass.end(), aiField) == vMyClass.end())

我还定义了operator==

 int operator ==(Field &Left,Field &Right)
 {
    return memcmp(&Left,&Right,sizeof(Field));
 }

int operator ==(Field &Right)
{
    return memcmp(this,&Right,sizeof(Field));
}

但我收到一条错误消息。

1>c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\algorithm(40) : error C2678: binary '==' : no operator found which takes a left-hand operand of type 'MyClass' (or there is no acceptable conversion)
1>        C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\guiddef.h(192): could be 'int operator ==(const GUID &,const GUID &)' [found using argument-dependent lookup]
1>        c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(85): or       'int operator ==(MyClass &,MyClass &)' [found using argument-dependent lookup]
1>        c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(70): or       'int MyClass::operator ==(MyClass &)'
1>        while trying to match the argument list '(MyClass, const MyClass)'
1>        c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\algorithm(74) : see reference to function template instantiation '_InIt std::_Find<std::_Vector_iterator<_Ty,_Alloc>,_Ty>(_InIt,_InIt,const _Ty &)' being compiled
1>        with
1>        [
1>            _InIt=std::_Vector_iterator<MyClass,std::allocator<MyClass>>,
1>            _Ty=MyClass,
1>            _Alloc=std::allocator<MyClass>
1>        ]
1>        c:\users\shmuelian\documents\visual studio 2008\projects\src\examples\DLgenerator\DLParser.h(108) : see reference to function template instantiation '_InIt std::find<std::_Vector_iterator<_Ty,_Alloc>,MyClass>(_InIt,_InIt,const _Ty &)' being compiled
1>        with
1>        [
1>            _InIt=std::_Vector_iterator<MyClass,std::allocator<MyClass>>,
1>            _Ty=MyClass,
1>            _Alloc=std::allocator<MyClass>
1>        ]
1>CommandArgParser.cpp
1>Generating Code...

最佳答案

它们需要是常量引用。 memcmp 真的非常糟糕 - 只需执行成员比较即可。

关于c++ - 如何在 std::vector 中找到一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6438100/

相关文章:

c++ - 中断创建arduino库

android - 无法在 Visual Studio 2015 的共享库(Android、iOS)中使用 nullptr

R - 将向量中的每个元素与其他向量的每个元素相加

c++ - vector 的交集

c++ - 模板二元运算符不明确?

c++ - 为每个节点分配深度

python - C++ - 无法编译 OpenCV 程序

c++ - std::vector 的复制构造函数如何操作?

c++ - 为什么 std::string 不采用空指针?

c++ - 有效地从字符串中读取括号中的两个逗号分隔的 float ,而不受全局语言环境的影响