[英]How to access member variable from nested class
我需要制作一个包含几个一维点的Solution类,可以为它指定一个中心和一个数字k以计算到该中心的k个最近点。
我的代码
class Solution {
private:
int center_;
struct Point {
int x;
bool operator<(const Point &other) const {
return (x - center_) * (x - center_) < (other.x - center_) * (other.x - center_);
}
};
public:
vector<int> findNearestKPoints(vector<int> &nums, int k, int center) {
center_ = center;
// vetor<int> to vector<Point>
vector<Point> points;
for (int num : nums) {
points.push_back({num});
}
// partition vector<Point>
nth_element(points.begin(), points.begin() + k - 1, points.end());
// vector<Point> to vector<int>
vector<int> res;
for (int i = 0; i < k; ++i) {
const Point &point = points[i];
res.push_back(point.val);
}
return res;
}
}
但它无法编译。
编译错误是
use of non-static data member 'center_' of 'Solution' from nested type 'Point'
那么如何解决呢? 也许还有其他方法可以计算最近的点。
您的Point
类没有访问Solution
类的权限,因此您不能在Point类代码中使用center_
。 这是因为Point
和Solution
是两个不同的类。
为了使您的解决方案有效,您需要向Point
提供有关Solution
类的信息,或者使用其他类进行比较。 我建议使用前者作为快速解决方案并使用lambda函数:
bool Point::less( const Solution& sol, const& Point p )
{
return abs(sol.center_ - x) < abs(sol.center_ - p.x);
}
并在您的findNearestKPoints中:
Solution sol{ center };
nth_element(nums.begin(), nums.begin() + k - 1, nums.end(),
[sol]( const& Point a, const& Point b )
{
return a.less( sol, b );
} );
最后,一个不相关的注释为何现在using namespace std
如此普遍?
您可以使用lambda并捕获center
:
nth_element(points.begin(), points.begin() + k - 1, points.end(),
[center]( const& Point a, const& Point b ) {
return abs(a.x - center) < abs(b.x - center);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.