假设我有一个名为dictionary的结构,其中包含两个char数组。我想根据第二个char数组按升序对字典类型数组'pair'进行排序。如何使用排序功能?我如何修改comp?
答案 0 :(得分:2)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
unsigned char message[100]; // string to be sorted
// (totally arbitrary length)
unsigned char sortOrder[256]; // string containing ASCII chars
// in their sort order
} Pair;
unsigned char rank[256]; // rank of each ASCII character
// qsort() comparison function
int sortByRank(const void *a, const void *b)
{
return ((int)rank[*(signed char *)a] - (int)rank[*(signed char *)b]);
}
// Creates an array by which a character's relative position can be found
// solely from its value. Characters of rank 0 will appear first when sorted.
// Characters not specified by sortOrder will appear first, since rank is
// global and automatically initialized to zeros.
void initRank(Pair pair)
{
int i;
for (i = 0; i < strlen(pair.sortOrder); i++)
rank[pair.sortOrder[i]] = i;
return;
}
int main()
{
// Create an example pair. Spaces will be the first characters in the
// sorted result.
Pair pair;
strcpy(pair.message, "this is a test message (123).");
strcpy(pair.sortOrder, " 321abcdefghijklm.nopqrstuvwxyz()");
// In this solution, initRank() will need to be called any time the
// sortOrder is changed.
initRank(pair);
// Sort using the global rank array set by initRank()
qsort(pair.message, strlen(pair.message), sizeof(char), sortByRank);
printf("Sorted message: %s\n", pair.message);
// Output:
// Sorted message: 321aaeeeghiim.sssssttt()
return 0;
}
由于rank []是全局的,这并不像以前那样优雅,但上述解决方案通常演示了如何利用C的排序函数以相当简单的方式基于第二个字符串进行自定义排序。