15

我正在尝试学习 c++,并尝试使用 sort 和 qsort。sort() 工作得很好,但 qsort 没有,我不知道为什么,所以你能帮我吗这是我试图编译的代码

#include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<algorithm>


using namespace std;

int compvar(const void *one, const void *two)
{
    int a = *((int*)one);
    int b = *((int*)two);
    if (a<b)
       return -1;
    if (a == b)
       return 0;
    return 1;   

}

void bvect(vector<int> &vec, int num)
{
     srand(time(NULL));
     for(int i=0; i<num; ++i)
             vec.push_back(rand()%1000 + 1);
}

void showvec(vector<int> vec)
{
     for (int i=0; i<vec.size(); ++i)
         cout<<vec[i]<<endl;
}


int main()
{
    vector<int>numbers;
    bvect(numbers, 1000);
    showvec(numbers);
    qsort(numbers.begin(), numbers.size(), sizeof(int), compvar);
    showvec(numbers);

    return 0;
}
4

1 回答 1

24

First of all, DON'T.

If you just want to muck about, you can replace iterators with actual pointers:

qsort(&numbers[0], numbers.size(), sizeof(int), compvar);

Apart from not doing all the work std::sort does, there is one unexpected thing about qsort. It is slower.

  1. sort (myvector1.begin(), myvector1.end());

  2. sort (myvector2.begin(), myvector2.end(), myfunction);

  3. sort (myvector3.begin(), myvector3.end(), myobject);

  4. qsort(&myvector4[0], myvector4.size(), sizeof(int), cmyfunction);

4 is the slowest, followed by 2 (function pointer passed to std::sort). 1 and 3 (default and functor) are the fastest (compiled with gnu's g++ with -O3 flag).

于 2012-09-06T21:04:54.847 回答