C++的vector容器使用qsort()和sort()

對vector容器定義的數組可以使用sort排序,這個很簡單

vector<int> test;
sort(test.begin(),test.end());

但是使用qsort時,我這裏報錯了

note: candidate function not viable: no known conversion from 'vector' to 'void *' for 1st argument; take the address of the argument with &
extern void qsort (void *__base, size_t __nmemb, size_t __size,
qsort(numbers,len,sizeof(int),compare);//錯誤用法
qsort(&numbers,len,sizeof(int),compare);//錯誤用法



qsort(&numbers[0],len,sizeof(int),compare);//錯誤用法
int compare(const void * arg1, const void *arg2)
{
    return (*(int*)arg1 - *(int*)arg2);
}

https://stackoverflow.com/questions/24303917/passing-vector-to-qsort

使用qsort,需要把使用原生的數組,也就是說要使用vector數組指針的地址,qsort的第一個參數要使用的要排序數組的指針。使用&entries[0]指向向量的第一個元素的指針,即可解決問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章