gpt4 book ai didi

c++ - 在 vector 中查找对象时出错

转载 作者:行者123 更新时间:2023-11-30 05:42:57 25 4
gpt4 key购买 nike

我有一个 Point我通过执行 Point p(a, b) 创建每个对象的类我想知道 Point 是否存在于我声明为 vector<Point> vPoint 的 vector 中.

我的一段代码如下;

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,

所以我想知道这个问题是否是由于在创建对象时没有使用指针/不支持非指针指向的对象的迭代器或其他原因造成的。

最佳答案

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

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

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

关于c++ - 在 vector 中查找对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30420371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com