【发布时间】:2020-08-29 23:55:20
【问题描述】:
我创建了一个名为 Point 的类,它只包含一个 x y 坐标元组。我还制作了一个类型点的向量并添加了点 (3,4)。现在我想用二进制搜索在这个向量中搜索该点,如果它返回真那么我想打印“是”,以确认该点存在于向量中。不幸的是,find 函数在 Point 类型的向量上不起作用,如何解决这个问题?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Point {
private:
double xval, yval;
public:
// Constructor uses default arguments to allow calling with zero, one,
// or two values.
Point(double x = 0.0, double y = 0.0) {
xval = x;
yval = y;
}
// Extractors.
double x() { return xval; }
double y() { return yval; }
};
int main()
{
vector<Point> points;
points.push_back(Point(3,4));
if (binary_search(points.begin(),points.end(),Point(3,4)))
{cout<<"The point exists"<<endl;}
return 0;
}
【问题讨论】:
-
您需要为您的班级提供
operator<,或者为binary_search提供自定义比较器 -
您可以这样做:提供自定义比较器,并确保元素按照比较器排序。