0

我有一个包含一个类的列表

list<PointTwoD> point

这是我的班级宣言

class PointTwoD:public locationdata
{
public:
  PointTwoD();
  PointTwoD(string,int,int,float,float,int,int);

  void set_x(int);
  int get_x();

  void set_y(int);
  int get_y();

  void set_civIndex(float);
  float get_civIndex();

  friend class MissionPlan;

private:
  int x;
  int y;
  float civIndex;

};

我正在尝试根据私有成员 civIndex 对列表进行排序。我曾尝试调用列表中的排序函数,但它不起作用。有人可以告诉我如何根据私人成员 civIndex 的值对列表进行排序吗?

4

1 回答 1

2

你可以通过在你的类中添加一个小于运算符来做到这一点:

  bool operator<(const PointTwoD& other) const
  {
      return civIndex < other.civIndex;
  }

如果您不想要一个通用的小于运算符但仍需要对列表进行排序,您可以提供一个执行相同操作的比较函数:

bool compare_PointTwoD(const PointTwoD& first, const PointTwoD& second)
{
    return first.get_civIndex() < second.get_civIndex();
}

并调用这样的排序:

std::list<PointTwoD> lpt;
lpt.sort(compare_PointTwoD);
于 2013-10-08T03:04:53.320 回答