在向量中查找对象时出错

时间:2015-05-24 05:27:55

标签: c++ vector iterator

我有一个Point类,我通过Point p(a, b)创建每个对象,我想查找Point是否存在于我声明为vector<Point> vPoint的向量中。

我的代码段如下;

Point p(a, b);
vector<Point>::iterator it = find(vPoint.begin(), vPoint.end(), p);
if(it != vPoint.end())
{
   // do something
}      

我得到的错误信息如下;     在

中包含的文件中
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:38:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:216:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:15:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:846:22: error: 
      invalid operands to binary expression ('Point' and 'const Point')
        if (*__first == __value_)
            ~~~~~~~~ ^  ~~~~~~~~
segmentpoints.cpp:72:33: note: in instantiation of function template specialization 'std::__1::find<std::__1::__wrap_iter<Point
      *>, Point>' requested here
                        vector<Point>::iterator it = find(vPoint.begin(), vPoint.end(), p);
                                                     ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/utility:403:1: note: 
      candidate template ignored: could not match 'pair<type-parameter-0-0, type-parameter-0-1>' against 'Point'
operator==(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iterator:574:1: note: 
      candidate template ignored: could not match 'reverse_iterator<type-parameter-0-0>' against 'Point'
operator==(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iterator:866:6: note: 
      candidate template ignored: could not match 'istreambuf_iterator<type-parameter-0-0, type-parameter-0-1>' against 'Point'
bool operator==(const istreambuf_iterator<_CharT,_Traits>& __a,

所以我想知道这个问题是否是由于在创建对象/迭代器时不使用指针而不支持指针未指向的对象或其他东西。

1 个答案:

答案 0 :(得分:1)

C ++不会自动创建比较运算符,因此您必须定义两个点相等的含义。例如,合理的实施可能是:

bool operator==(const Point& a, const Point& b) {
    return a.x == b.x && a.y == b.y;
}

另请注意,如果您的代码需要它,您还必须实现operator !=,因为如果给定!=,C ++不会自动实现==,反之亦然。