以下代码段旨在将所有points
存储在priority_queue(即mainFunc
)中的封闭类Solution
的成员函数pq
中,以便全部{{ 1}}按照与points
的距离顺序排列。但是,编译器报告错误:
origin
然后我将error: invalid use of non-static data member 'Solution::ori'
的第3行更改为Point ori
并在static Point ori
函数中将ori
更改为Solution::ori
,发生链接错误:< / p>
distance(Point p)
有人可以帮我这个吗?提前谢谢!
undefined reference to 'Solution::ori'
答案 0 :(得分:2)
您可以修改Comparator
声明,使其在其构造函数中获得某个Point
值:
class Solution {
private:
Point ori;
class Comparator {
public:
// Save the value in the functor class
Comparator(const Point& origin) : origin_(origin) {}
// calculate the euclidean distance between p and origin
int distance(Point p) {
return pow(p.x-origin_.x, 2) + pow(p.y-origin_.y, 2);
}
// overload the comparator (), the nearest point to
// origin comes to the first
bool operator() (Point l, Point r) {
if (distance(l) > distance(r)) {
return true;
}
}
private:
Point origin_;
};
public:
/*
* @param points: a list of points
* @param origin: a point
*/
void mainFunc(vector<Point> points, Point origin) {
ori = origin;
priority_queue<Point, vector<Point>> pq(Comparator(ori));
// ^^^^^^^^^^^^^^^
// Pass an instance of
// the functor class
for (int i = 0; i < points.size(); i++) {
pq.push(points[i]);
}
}
};