我有qsort
麻煩,如果有人能幫助我,我會很感激。快速排序處理指針
另外,我還搜查SO很多之前詢問,但沒有成功。
下面是我的程序大致設置:
〜.H〜
class playerClass{
playerClass() { }
...
double average;
};
class Stats{
void update(...);
...
playerClass *ar[1201];
};
〜〜的.cpp
void update(...){
playerClass *p = new playerClass();
...
for (int i = 0; i < count; i++){
...
ar[j]->average = (ar[j]->hits)/(ar[j]->atBats);
cout << "Average: " << ar[j]->average << endl;
/* Prints Averages correctly, but I need everything to be sorted by
the Averages, and I am instructed to use qsort */
qsort(*ar, count, sizeof(playerClass*), compare);
cout << "Sorted average: " << ar[j]->average << endl;
}
}
int compare (const void *a, const void *b){
playerClass *x = (playerClass*)a;
playerClass *y = (playerClass*)b;
/* I believe that I'm not correctly accessing the Averages with
the two statements above, I have tried many different variations
of them, but I am not actually able to access the averages correct.
Can someone please help me, so that way I can get over this obstacle
and continue this assignment? */
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
C++有許多很好的[算法在其標準庫(http://en.cppreference.com/w/cpp/algorithm),那些更適合對於C++而言,比像'qsort'這樣的舊C函數更爲重要。我建議你閱讀['std :: sort'](http://en.cppreference.com/w/cpp/algorithm/sort)。 –
還要注意,'ar'是一個指針數組,這意味着'* ar'不會達到你期望的值。我還建議你閱讀['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –
@JoachimPileborg - 同意;但「任務」要求使用'qsort' ... – Floris