【问题标题】:Sorting list with extra arguments to comparison function带有额外参数的排序列表到比较函数
【发布时间】:2017-01-24 06:37:46
【问题描述】:

鉴于以下

class Coordinate {
  int i,j;
};

list<shared_ptr<Coordinate>> coordinates;

Coordinate 只是我的代码真正包含的更简单的版本。)我想根据到给定坐标iCenter,jCenter 的最小欧几里得距离对list 进行排序。最接近此坐标的Coordinate 应该在列表coordinates 中的第一个位置。此外,我想使用以下结构

struct ComparatorForCoordinate {
  bool operator() (const shared_ptr<Coordinate>& c1, const shared_ptr<Coordinate>& c2) {
    // return distance(c1 to center) > distance(c2 to center)
  }
};

// sorting:
coordinates.sort(ComparatorForCoordinate());

我的问题是我的operator() 需要知道坐标iCenter,jCenter。如何将这两个双精度值传递给比较函数?天真地试图让操作员另外有两个中心位置的双参数是行不通的。如果可以的话,这个电话对我来说会很棒:

coordinates.sort(ComparatorForCoordinate(iCenter,jCenter));

【问题讨论】:

  • 我调整了标题,并添加了 STL 标签,希望其他用户更容易找到这个问题(和答案)。如果您不喜欢这些更改,请随时恢复。

标签: c++ sorting stl


【解决方案1】:

您可以向比较器添加状态:

struct ComparatorForCoordinate {
  ComparatorForCoordinate(Coordinate center) : _center(center) {}

  bool operator() (const shared_ptr<Coordinate>& c1, const shared_ptr<Coordinate>& c2) const {
    return distance(c1, _center) > distance(c2, _center);
  }

private:
  Coordinate _center;
};

// sorting:
coordinates.sort(ComparatorForCoordinate(center));

【讨论】:

  • 这行得通...如果我现在有两个不同的比较器功能,例如一种根据欧几里得距离排序,一种仅根据i-值之间的距离进行排序。我需要两个structs 作为比较器还是可以将这两个比较函数放在同一个结构中?
  • @Kapa11:您可以在比较器构造函数中添加一个bool euclidean 参数,并在每次比较时检查它。但是编写一个单独的比较器会更有效和更惯用。
  • 非常感谢,这就是我搜索的内容:)
猜你喜欢
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2020-02-28
  • 1970-01-01
相关资源
最近更新 更多