用的std ::排序元素块排序() [英] Sorting by blocks of elements with std::sort()
问题描述
我有边缘的数组,其定义为一个C数组双打,其中每4双打定义一个边缘,这样的:
I have an array of edges, which is defined as a C-style array of doubles, where every 4 doubles define an edge, like this:
double *p = ...;
printf("edge1: %lf %lf %lf %lf\n", p[0], p[1], p[2], p[3]);
printf("edge2: %lf %lf %lf %lf\n", p[4], p[5], p[6], p[7]);
所以我想用的std ::排序()
由边长排序。如果这是一个结构边缘{双X1,Y1,X2,Y2; };边缘* P;
,我会好到哪里去。
So I want to use std::sort()
to sort it by edge length. If it was a struct Edge { double x1, y1, x2, y2; }; Edge *p;
, I would be good to go.
但是,在这种情况下,双阵列具有块大小不是由指针型pssed前$ P $。 的qsort()
允许你明确指定块大小,但的std ::排序()
推断块大小的指针类型。
But in this case, the double array has a block size that is not expressed by the pointer type. qsort()
allows you to explicitly specify the block size, but std::sort()
infers the block-size by the pointer type.
有关性能方面的原因(包括内存使用和CPU),让我们说,这是不可取的创建新阵列,或以某种方式变换的阵列。出于性能方面再次,让我们说,我们要使用的std ::排序()
而不是的qsort()
For performance reasons (both memory-usage and CPU), let's say that it's undesirable to create new arrays, or transform the array somehow. For performance reasons again, let's say that we do want to use std::sort()
instead of qsort()
.
是否有可能调用的std ::排序()
不会对转换数据浪费一个CPU周期?
Is it possible to call std::sort()
without wasting a single CPU cycle on transforming the data?
这是显而易见的方法是尝试强制转换指针:
An obvious approach is to try to force-cast the pointer:
double *p = ...;
struct Edge { double arr[4]; };
Edge *p2 = reinterpret_cast<Edge*>(p);
std::sort(...);
但我怎么确保数据正确对齐?另外,我怎么确保它总是会在所有的平台和架构正确对齐?
But how do I make sure the data is aligned properly? Also, how do I make sure it will always be aligned properly on all platforms and architectures?
或者,我可以使用的typedef双[4]边缘;
推荐答案
怎么样有一个重新排序向量?您初始化1..1 / L载体,传递的std ::那种比较元素I1 * L..i1 * L + L到I2 * L..i2 * L + L,而当你的载体正确排序的比较,根据新的秩序重新排序C数组。
How about having a reordering vector? You initialize vector with 1..N/L, pass std::sort a comparator that compares elements i1*L..i1*L+L to i2*L..i2*L+L, and when your vector is properly sorted, reorder the C array according to new order.
在回应评论:是的事情变得复杂,但它可能只是好复杂!看看<一个href=\"http://stackoverflow.com/questions/838384/reorder-vector-using-a-vector-of-indices\">here.
In response to comment: yes things get complicated, but it may just be good complication! Take a look here.
这篇关于用的std ::排序元素块排序()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!