结构比较器访问 C++ 中的另一个字段
Struct comparator accessing another field in c++
我正在尝试实施格雷厄姆扫描,我想做这样的事情:
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());
您可以给 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));
我正在尝试实施格雷厄姆扫描,我想做这样的事情:
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());
您可以给 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));