我可以对单词指针数组进行排序,使它们按字母顺序排序,问题是我需要对整数数组(特定单词的使用次数)进行排序,以便整数与它们的位置相同各自的话:
我的代码:
for (i = 0; i < numWords; i++) {
// prints out the words and their frequency respectively
printf("%s - %d\n", dictionary[i], frequency[i]);
}
//sorts the dictionary so that the words are 'alphabetical'
qsort(dictionary, numWords, sizeof(char *), rstrcmp);
printf("\nafter qsort\n"); //checkmark
for (i = 0; i < numWords; i++) {
// prints the word list alphabetically, but the frequencies are no longer matched
printf("%s - %d\n", dictionary[i], frequency[i]);
}
Run Code Online (Sandbox Code Playgroud)
...比较功能V.
int rstrcmp(const void *p1, const void *p2) {
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
Run Code Online (Sandbox Code Playgroud)
一个简单的事情是使用结构来存储字/频率对,然后对这些结构的数组进行排序.
例如:
struct WordFrequency
{
const char * word;
int frequency;
} wordFreqs[numWords]; // Assumes numWords is static/global and constant...
Run Code Online (Sandbox Code Playgroud)
然后:
for (i = 0; i < numWords; i++) {
printf("%s - %d\n", dictionary[i], frequency[i]);
wordFreqs[i].word = dictionary[i];
wordFreqs[i].frequency = frequency[i];
}
//sorts the dictionary so that the words are 'alphabetical'
qsort(wordFreqs, numWords, sizeof(struct WordFrequency), wfcmp);
for (i = 0; i < numWords; i++) {
printf("%s - %d\n", wordFreqs[i].word, wordFreqs[i].frequency);
}
Run Code Online (Sandbox Code Playgroud)
和:
int wfcmp(const void *p1, const void *p2) {
return strcmp(((const struct WordFrequency *)p1)->word, ((const struct WordFrequency *)p2)->word);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2263 次 |
| 最近记录: |