c++ - qsort 类对象列表

标签 c++ list class qsort

我正在为现有库编写排序代码,因此无法更改数据模型 我有以下内容

 class Point
 {

   //Some functions 
   public:
       float x, y, z;

  };

int less_than_key (const void *arg1, const void *arg2)
 {

      Point *r1 = (Point*) arg1;
      Point *r2 = (Point*) arg2;

      if(r1->z < r2->z )
        return -1;

     else if(r1->z > r2->z )
       return 1;
    else
       return 0;
}

int main()
{
   list<Point> myPoints; 

    Point p;
    p.x = 0;
    p.y = 0;
    p.z = 0;
    myPoints.push_back(p);

    p.x = 0;
    p.y = 0;
    p.z = 6;
    myPoints.push_back(p);

    p.x = 0;
    p.y = 0;
    p.z = 2;
    myPoints.push_back(p);

    for(int i=0; i<myPoints.size(); i++)
      cout<<" Point "<<p[i].x<<", "<<p[i].y<<", "<<p[i].z<<"\n";

    qsort(&myPoints, myPoints.size(), sizeof(Point), less_than_key);

    for(int i=0; i<myPoints.size(); i++)
      cout<<"Point "<<p[i].x<<", "<<p[i].y<<", "<<p[i].z<<"\n";
 }

我想根据 z 值对对象进行排序。 我期望的输出如下

 Before sorting 
 Point 0, 0, 0
 Point 0, 0, 6
 Point 0, 0, 2

 After sorting 
 Point 0, 0, 0
 Point 0, 0, 2
 Point 0, 0, 6

当我运行以下代码时,它在排序调用期间崩溃,并且出现以下错误

  terminated with signal 11

我在其他解决方案中读到我应该按以下方式传递列表

   qsort(&myPoints[0], myPoints.size(), sizeof(Point), less_than_key);

但是当我尝试编译它时,我得到以下内容

  no match for 'operator[]' (operand types are 'std::list<Point>' and 'int')

最佳答案

您可以将 std::sort 与 lambda 表达式一起使用,这是一个示例:

#include <algorithm>

std::list<Point> myPoints;

//adding points to list...

std::sort(myPoints.begin(), myPoints.end(), [](const Point& lhs, const Point& rhs)
{
   return lhs.z < rhs.z;
});

for(int i=0; i<myPoints.size(); i++)
  cout<<"Point "<<p[i].x<<", "<<p[i].y<<", "<<p[i].z<<"\n";

上面的代码将排序,然后打印排序后的点列表

关于c++ - qsort 类对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45492005/

相关文章:

c++ - C++虚函数除了vtable怎么实现?

c++ - parallel_for (Inter TBB) 是否存在类似于我们在 std::function 上看到的开销?

c++ - std::string 插入方法有不明确的重载?

c# - 如何使用 Linq 在 C# 列表中添加缺失值列表

Python:将字典列表转换为 json

python - 创建表并从字典中的列表中排序数据

html - 什么是 HTML 中的类?

c++ - 原始变量是否在 C++ 中被垃圾收集

java - 什么是java pojo类、java bean、普通类?

css - HTML5 和 Bootstrap 类 ="container",它可以应用于 body 还是只应用于 div?