Shihao Xu
Shihao Xu

Reputation: 1200

How to access member variable from nested class

I need to make a Solution class that holds several 1D points and it can be given a center and a number k to calculated the k nearest points to this center.

My code,

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;
    }
}

but it cannot compile.

The compile error is

use of non-static data member 'center_' of 'Solution' from nested type 'Point'

So how to fix it? Maybe there are other ways to calculate nearest points.

Upvotes: 1

Views: 644

Answers (2)

O&#39;Neil
O&#39;Neil

Reputation: 3849

You can use a lambda and capture the 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);
            });

Upvotes: 1

Nonanon
Nonanon

Reputation: 560

Your Point class does not have access to the Solution class, and so you cannot use center_ in your Point class code. This is because Point and Solution are two different classes.

To make your solution work, you will need to provide information about your Solution class to your Point, or use a different class to do your comparison. I would suggest the former for a quick solution and use lambda functions:

bool Point::less( const Solution& sol, const& Point p )
{
    return abs(sol.center_ - x) < abs(sol.center_ - p.x);
}

and in your 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 );
    } );

And on a final, unrelated note why is using namespace std so common now?

Upvotes: 4

Related Questions