结构比较器访问 C++ 中的另一个字段

时间:2020-12-31 16:04:59

标签: c++ sorting struct grahams-scan

我正在尝试实施 Graham 扫描,并且我想做这样的事情:

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++ 中实现相同的想法,因为我只能传入 compar 的函数,我不知道如何访问最低点。

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());

1 个答案:

答案 0 :(得分: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 的整个向量似乎很浪费,而且它也不太具有描述性。为什么不制作一个漂亮的 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));
相关问题