C++ 尝试将 qsort 与向量一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12308243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to use qsort with vector
提问by user1653150
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
我正在尝试学习 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;
}
回答by Ivan
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.
除了没有完成所有的工作之外std::sort
,还有一件意想不到的事情qsort
。它更慢。
sort (myvector1.begin(), myvector1.end());
sort (myvector2.begin(), myvector2.end(), myfunction);
sort (myvector3.begin(), myvector3.end(), myobject);
qsort(&myvector4[0], myvector4.size(), sizeof(int), cmyfunction);
sort (myvector1.begin(), myvector1.end());
sort (myvector2.begin(), myvector2.end(), myfunction);
sort (myvector3.begin(), myvector3.end(), myobject);
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).
4 是最慢的,其次是 2(传递给 的函数指针std::sort
)。1 和 3(默认和函子)是最快的(用带有 -O3 标志的 gnu 的 g++ 编译)。