我有一个大小为 4N 的 float 数组,我想通过将每组 4 个 float 视为一个项目来对它们进行排序 - 比如 (x, y, z, w),然后我想根据它们进行排序关于 z 值。
我目前的方法是制作一个数组
struct A
{
float *p;
int index;
bool operator < (const A &obj)
{
return ( *(p + 2) < *(obj.p + 2) );
}
};
对其使用std::sort
,然后创建一个大小为4N的新数组,并根据相应的索引进行填充。
我确定有一种方法可以就地对其进行排序,但我不知道该怎么做
最佳答案
像这样:
struct A
{
float x, y, z, w;
bool operator < (const A &other) const
{
return z < other.z;
}
};
enum { N = 1000 };
float v[4 * N];
...
A *w = reinterpret_cast<A*>(v);
sort(w, w + N);
关于c++ - 如何使用 std::sort 以 'custom' 方式就地对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49472208/