尝试使用qsort与向量 [英] Trying to use qsort with vector
问题描述
我想学习c ++,并尝试使用sort和qsort。 sort()的工作原理很好
但qsort不,我不知道为什么,所以可以帮助我
这是我试图编译的代码
I'm trying to learn c++ and was trying using sort and qsort. sort() works just fine but qsort doesn't, I don't know why, so can you help me please this is the code I was trying to compile
#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;
}
推荐答案
首先, T。
如果你只是想嘲笑,你可以用实际指针替换迭代器:
If you you just want to mock about, you can replace iterators with actual pointers:
qsort(&numbers[0], numbers.size(), sizeof(int), compvar);
除了不执行所有的工作std :: sort,还有一个意想不到的事情qsort。
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()); / code>
1 - sort (myvector1.begin(), myvector1.end());
2 - sort(myvector2.begin(),myvector2.end(),myfunction);
3 - sort(myvector3.begin(),myvector3.end(),myobject);
4 - qsort(& myvector4 [0],myvector4size(),sizeof(int),cmyfunction);
4是最慢的,后面是2(函数指针传递给std :: sort)。 1和3(默认和函子)是最快的(用gnu的g ++和-O3标志编译)
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)
这篇关于尝试使用qsort与向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!