假设我有一个名为字典的结构,其中包含两个字符数组。我想根据第二个字符数组升序对字典类型数组“对”进行排序。如何使用排序功能做到这一点?我需要如何修改comp?
问问题
1283 次
1 回答
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 的排序函数以相当简单的方式基于第二个字符串进行自定义排序。
于 2013-01-12T16:55:46.313 回答