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;
}
As the name suggests, qsort function uses QuickSort algorithm to sort the given array, although the C standard does not require it to implement quicksort.
C library function - qsort() The C library function void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) sorts an array.
Sorting a Vector in C++ in Ascending order A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With