2

我正在尝试实现格雷厄姆扫描,我想做这样的事情:

private static void sortByPolar(Point[] points, Point r) {
    Arrays.sort(points, (p, q) -> {
    int compPolar = ccw(p, r, q);
    int compDist = dist(p, r) - dist(q, r); 
    return compPolar == 0 ? compDist : compPolar;
});

其中点 r 是最底点。但是,我正在努力在 c++ 中实现同样的想法,因为我只能传入比较的函数,我不知道它如何访问最低点。

struct compar {
  vector<vector<int>> lowest;
  bool operator()(vector<int> const& a, vector<int> const& b) {
    cout<<lowest[0]<<endl;    // throws an error, how do I get this function access to lowest?
    return // TODO;
  }
};

// in another function:
sort(points.begin(), points.end(), compar());
4

1 回答 1

3

您可以为compar构造函数提供所需数据的参数,然后在创建临时实例时将其作为参数传递:

struct compar {
  explicit compar(vector<int> const& lowest) : m_lowest(lowest) {}
  
  bool operator()(vector<int> const& a, vector<int> const& b) {
    cout<<m_lowest[0]<<endl;
    return // TODO;
  }

private:
  vector<int> m_lowest;
};

// in another function:
vector<int> lowestPoint;  // (get this from somewhere)
sort(points.begin(), points.end(), compar(lowestPoint));

顺便说一句,int每个点的两个 s 的整个向量似乎很浪费,而且描述性也不是很好。为什么不做一个漂亮的Point类型?

struct Point
{
   int x, y;
};

struct PointComparator
{
   explicit PointComparator(const Point& lowest)
      : m_lowest(lowest)
   {}
   
   bool operator()(const Point& a, const Point& b)
   {
      std::cout << m_lowest[0] << std::endl;
      return; // TODO
   }

private:
   Point m_lowest;
};

// in another function:
Point lowestPoint;  // (get this from somewhere)
std::sort(points.begin(), points.end(), PointComparator(lowestPoint));
于 2020-12-31T16:07:32.713 回答