本文介绍了使用的qsort两个数组排序同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
,使得它们按字母顺序排列我可以排序指针字的阵列,所述问题是,我还需要进行排序的整数阵列(该特定字用于的次数),这样,整数是在相同的把它们各自的话说:
我的code:
为(i = 0; I< NUMWORDS;我++){
//分别打印出的文字和它们的频率
的printf(%S - %d个\\ N,字典[I],频率[I]);
}//排序的字典,这样的话是按字母
的qsort(字典,NUMWORDS,sizeof的(字符*),rstrcmp);
的printf(\\ n在的qsort \\ n); //复选标记对于(i = 0; I< NUMWORDS;我++){
//打印单词列表按字母顺序,但频率是不再匹配
的printf(%S - %d个\\ N,字典[I],频率[I]);
}
...比较函数V
INT rstrcmp(常量无效* P1,常量无效* P2){
返回STRCMP(*(char * const的*)P1,*(char * const的*)P2);
}
解决方案
一个简单的事情将是使用结构来存储字/频率对,然后进行排序,这些结构的数组。
例如:
结构WordFrequency
{
为const char *字;
INT频率;
} wordFreqs [NUMWORDS] //假设NUMWORDS是静态/全局,不断...
然后:
为(i = 0; I< NUMWORDS;我++){
的printf(%S - %d个\\ N,字典[I],频率[I]);
wordFreqs [I] .word =词典[I]
wordFreqs [I]。频率=频率[I]
}//排序的字典,这样的话是按字母
的qsort(wordFreqs,NUMWORDS,sizeof的(结构WordFrequency),wfcmp);对于(i = 0; I< NUMWORDS;我++){
的printf(%S - %d个\\ N,wordFreqs [I] .word,wordFreqs [I]。频率);
}
和
INT wfcmp(常量无效* P1,常量无效* P2){
返回的strcmp(((常量结构WordFrequency *)P1) - >字,((常量结构WordFrequency *)P2) - >字);
}
I can sort a array of pointers to words so that they are ordered alphabetically, the problem is that I need to ALSO sort an integer array (the number of times that specific word is used) so that the integers are in the same place as their respective words:
my code:
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]);
}
...comparison function V
int rstrcmp(const void *p1, const void *p2) {
return strcmp(*(char * const *)p1, *(char * const *)p2);
}
解决方案
A simple thing to do would be to use a struct to store word/frequency pairs and then sort an array of these structs.
For example:
struct WordFrequency
{
const char * word;
int frequency;
} wordFreqs[numWords]; // Assumes numWords is static/global and constant...
Then:
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);
}
And:
int wfcmp(const void *p1, const void *p2) {
return strcmp(((const struct WordFrequency *)p1)->word, ((const struct WordFrequency *)p2)->word);
}
这篇关于使用的qsort两个数组排序同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!