【问题标题】:How to sort w.r.t. certain parameter using C++ custom compare function?如何排序 w.r.t.使用 C++ 自定义比较函数的某些参数?
【发布时间】:2020-03-23 11:05:48
【问题描述】:

我正在尝试通过它们的极角 w.r.t 对平面上的点进行排序。 O点。代码的简化版如下所示:

bool comparePolar(point A, point B, point O){
    //if point B lies to the left of the edge OA, return false
    //return true
}

那么,如何在调用排序函数时将点O传递给这个函数,它将使用comparePolar作为它的比较函数?

【问题讨论】:

    标签: c++ sorting parameter-passing custom-compare


    【解决方案1】:

    您需要构造一个包含O(或对它的引用)的函数对象。最简单的方法是使用 lambda

    // initialised wherever
    std::vector<point> points;
    point O;
    
    // Capture O by value
    auto cmp = [O](point A, point B) { return comparePolar(A, B, O); };
    std::sort(points.begin(), points.end(), cmp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多