PDA

View Full Version : error with qsort



vinaysagar
15th July 2014, 10:34
hi
i had pblm using qsort to sort arrays. i used Qvector but it didnt wrk. plz help me with this
here is my code:



public:
explicit MainWindow(QWidget *parent = 0);
QVector <double> temp_array;
int comp(const void * a,const void * b);
~MainWindow();

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qStablesort(temp_array, temp_array.size(), sizeof(double), int comp);

}
int MainWindow:: comp(const void * a,const void * b)
{

if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;
else return 0; ;
}

Lesiok
15th July 2014, 10:43
Why not use the standard features of Qt : qSort( Container & container ) (http://qt-project.org/doc/qt-4.8/qtalgorithms.html#qSort-3) or qStableSort( Container & container ) (http://qt-project.org/doc/qt-4.8/qtalgorithms.html#qStableSort-3) ?

yeye_olive
15th July 2014, 11:22
hi
i had pblm using qsort to sort arrays. i used Qvector but it didnt wrk. plz help me with this
here is my code:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qStablesort(temp_array, temp_array.size(), sizeof(double), int comp);

}


"it didnt wrk" is not very informative. What were you expecting? What did you get instead?

Your call to qStablesort() is syntactically incorrect (invalid C++, nothing to do with Qt). In addition, you pass 4 arguments, while no variants of this method with more than 3 parameters seem to exist. Here is a link to the documentation of qStablesort(): http://qt-project.org/doc/qt-4.8/qtalgorithms.html#qStableSort. By the way, as implied by Lesiok, you do not need a custom comparison function if all it does is mimic the < operator; and your (non static!) function does not have the correct prototype anyway (this is C++, not C's qsort).

From Qt 5.0 on, these generic algorithms are deprecated. I suggest you call the standard C++ equivalent instead: http://en.cppreference.com/w/cpp/algorithm/stable_sort.

ChrisW67
15th July 2014, 21:24
It might be more useful if the vector actually contained some data also.