我正在为现有库编写排序代码,因此无法更改数据模型 我有以下内容
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/