[英]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.