根据类私有成员对包含类的列表进行排序

时间:2013-10-08 02:59:18

标签: c++ list debugging stl

我有一个包含类

的列表
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对列表进行排序。我试过在列表上调用sort函数,但它不起作用。 有人可以告诉我如何根据私有成员civIndex ??

的值对列表进行排序

1 个答案:

答案 0 :(得分:2)

您可以通过在课程中添加一个小于运算符来完成此操作:

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

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

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

并调用这样的排序:

std::list<PointTwoD> lpt;
lpt.sort(compare_PointTwoD);
相关问题