我在巨大的文本文件中有最频繁的单词结构,指向 char 的字段指针数组是单词,字段计数是它们的频率。我的问题是如何将它们从最长的字长到最低的字长排序——以便很好地向用户显示?代码:
typedef struct pair {
char * a[20000];
int count[32000];
} Pair;
示例打印:
printf("%d, %d, %d\n", bag.count[0], bag.count[1], bag.count[2]); // -> 8, 7, 3
printf("%s, %s, %s\n", bag.a[0], bag.a[1], bag.a[2]); // -> abbes, abbey, abhor
最佳答案
我建议将结构/数组从里到外翻转。
将数组放在 struct
中感觉不对。因为你主要有一对东西,其次你想要这些东西的一个数组。你明白我的意思吗?
看起来像这样:
typedef struct pair
{
char* word;
int count;
} Pair;
Pair pairs[32000];
您还需要知道填充了多少对。 (无论如何你都需要这个。):
int index; // Index of next free pair.
然后使用 C 标准 qsort()
:
#include <stdlib.h>
...
int comparePairs(const void *pairA, const void *pairB)
{
Pair* a = (Pair*)pairA;
Pair* b = (Pair*)pairB;
return strlen(a->word) - strlen(b->word);
}
qsort(pairs, index, sizeof(Pair), comparePairs);
index
将从 0
开始,这表示下一个空闲的 Pair
位于该索引处。添加一个元素将是:
pairs[index].word = someWord; // someWord must be allocated elsewhere!
pairs[index].count = 1;
index++;
请注意,因为您的结构只有一个 char
指针,所以 someWord
必须分配到别处。如果没有自动内存管理,这将非常麻烦。更好的替代方法是使用以下结构 strcpy()
in 中的单词:
typedef struct pair
{
char word[50]; // Assumes a word is NEVER longer than 49 characters.
int count;
} Pair;
添加一个新元素会变成:
strncpy(pairs[index].word, someWord, 50 - 1);
pairs[index].count = 1;
index++;
上面的strncpy()
最多复制49个字符。您需要确保您明智地选择了这个 50 或任何大小,以确保 strncpy()
永远不会开始切断您很长的单词的结尾。
但是当然要知道您是否必须添加一个新的或简单地增加现有的计数,您首先需要使用一个简单的循环搜索现有的 Pair
。
关于c - 在 C 中对客户结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341416/