Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 基于qsort的数组排序结构_C_Sorting_Structure - Fatal编程技术网

C 基于qsort的数组排序结构

C 基于qsort的数组排序结构,c,sorting,structure,C,Sorting,Structure,通常,对结构对象数组进行排序很容易。考虑一个结构数组(AOS)< /P> 我首先用对的值填充这个结构数组 如果我现在想根据integer字段对这个结构数组进行排序,我可以使用libcqsort函数,通过使用一个比较函数,该函数接受两个整数参数 现在考虑用SOA格式替换AOS格式中的上述结构 #define ITEMS 10 typedef struct MyStruct { char a[ITEMS]; int b[ITEMS]; }tMyStruct; tMyStruct mystr

通常,对结构对象数组进行排序很容易。考虑一个结构数组(AOS)< /P> 我首先用对的值填充这个结构数组

如果我现在想根据integer字段对这个结构数组进行排序,我可以使用libcqsort函数,通过使用一个比较函数,该函数接受两个整数参数

现在考虑用SOA格式

替换AOS格式中的上述结构
#define ITEMS 10

typedef struct MyStruct
{
 char a[ITEMS];
 int  b[ITEMS];
}tMyStruct;

tMyStruct mystruct;
现在我仍然可以使用qsort对整数数组b字段进行排序,但是这次我需要额外对a(字符数组)进行排序,w.r.t排序顺序为b

所以我的问题是,对于以SOA格式而不是通常的AOS格式排列的数据,什么是一种可能有效的排序方法?


有人能帮我吗?谢谢

最好的方法可能是使用助手数组:

int helper[ITEMS];

int helper_cmp(const void *a, const void *b);

for (i = 0; i < ITEMS; ++i)
    helper[i] = i;
qsort(helper, ITEMS, sizeof(*helper), helper_cmp);
然后,在
qsort
之后,helper数组将包含重新排列的
b
索引,告诉它应该如何排序

您可以使用此数组来重新排列
mystruct.a
mystruct.b



请注意,这并不像排序“结构数组”那样有效。我不知道您的应用程序,但我猜“数组结构”,即数组的字段相互关联,从一开始就不是一个好主意。也就是说,如果
b
的排序影响
a
的排序,那么它们可能属于同一个概念元素(如果需要,可以称之为class),最好将它们组合在一个
结构中,而不是助手建议,使用qsort()无法做到这一点。对于这种情况,我将编写自己的排序函数。为了实现速度和易于编写的最佳平衡,我发现插入排序适用于小数组,合并排序适用于大数组。

a w.r.t排序顺序为b
。你能帮我翻译一下这个吗?@AljoshaBre它的意思是“a关于b的排序顺序”,我想他想对数组
a
b
进行排序,以便它们都根据
b
的数据进行排序。换句话说,把所有的数据对放在一起。你用C++标记了这个,你对C++解决方案感兴趣吗?如果
std::sort
只通过
std::less
std::swap
工作,那么您可以通过提供一个自定义
std::swap
来解决您的问题,该自定义
std::swap
也可以处理
a
s。SOA方法经常用于多核优化(SIMDization、缓存效率)和GPU(CUDA)。
int helper[ITEMS];

int helper_cmp(const void *a, const void *b);

for (i = 0; i < ITEMS; ++i)
    helper[i] = i;
qsort(helper, ITEMS, sizeof(*helper), helper_cmp);
int helper_cmp(const void *a, const void *b)
{
    int first = *(const int *)a;
    int second = *(const int *)b;
    int b_first = mystruct.b[first];
    int b_second = mystruct.b[second];
    // compare b_first and b_second
}