【发布时间】:2020-12-04 15:36:42
【问题描述】:
我在C中搜索了后缀数组的实现,但是我看到的所有程序都是使用排序的C++。我不确定如何使用 C 的内置函数 qsort() 代替 C 的 sort() 函数。 我们可以在不使用 qsort() 的情况下实现后缀数组吗? 或者 C语言中如何使用qsort()实现后缀数组?
这是我从 geeksforgeeks.com 获得的代码:
int cmp(struct suffix a, struct suffix b)
{
return strcmp(a.suff, b.suff) < 0? 1 : 0;
}
int *buildSuffixArray(char *txt, int n)
{
// A structure to store suffixes and their indexes
struct suffix suffixes[n];
// Store suffixes and their indexes in an array of structures.
// The structure is needed to sort the suffixes alphabatically
// and maintain their old indexes while sorting
for (int i = 0; i < n; i++)
{
suffixes[i].index = i;
suffixes[i].suff = (txt+i);
}
// Sort the suffixes using the comparison function
// defined above.
sort(suffixes, suffixes+n, cmp);
// Store indexes of all sorted suffixes in the suffix array
int *suffixArr = new int[n];
for (int i = 0; i < n; i++)
suffixArr[i] = suffixes[i].index;
// Return the suffix array
return suffixArr;
}
cmp 函数正在比较结构数据类型,而我在使用 qsort() 时遇到错误,表示只允许 void 输入。
【问题讨论】:
-
是什么阻止您使用
qsort? -
您使用
qsort()的方式与在任何其他上下文中使用它的方式相同,后缀数组有什么不同? -
听起来您只是不确定如何使用
qsort()对结构数组进行排序。 -
那么你能指导我如何使用 qsort
-
首先阅读man page。这描述了它的工作原理并有一个示例,因此应该可以帮助您入门。
标签: c suffix-array