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;
}
qsort
on a vector is just plain nuts. – Aniqsort
?! – Ricker&numbers[0]
instead ofnumbers.begin()
. – Gubernatorialint a = *((int*)one);
the outermost parentheses aren't needed. – Electuaryif (a == b) return 0; return 1;
could be replaced byreturn (a > b);
but that is minor compared to the horror of not usingstd::sort
in the first place. – Koodoo